Python – 替代前后和
Python语言中最重要的数据类型之一是列表。Python中有各种内置方法可以用于操作列表项,如append()、insert()、extend()等等。有多种方法可以找到一个数组的替代前后和。给定一个有n个元素的数组,流程是将第一个元素加到数组的最后一个元素上,将第二个元素加到倒数第二个元素上,依此类推,直到所有元素都被加在一起。例如,我们来看看下面的数组:
[40, 50, 20, 30]
替代前后和计算为(40+30) + (50+20) = 140
方法
方法1:使用条件语句
方法2:使用zip函数
方法1:使用条件语句的Python程序来计算替代前后和
条件语句用于比较num和ran,然后对列表元素进行加法运算,并返回值为60和-50。
算法
- 步骤1 – 初始化列表。
-
步骤2 – 将变量num初始化为0,将ran设置为给定列表的长度减1。
-
步骤3 – 初始化空列表。
-
步骤4 – 当num小于ran时:
- 如果标志为真,则将输入列表中索引为num和ran的元素添加到空列表中。
-
如果标志为假,则将输入列表中索引为num和ran的元素的负和添加到空列表中。
-
步骤5 – 递增num,递减变量”ran”。
-
步骤6 – 在另一种情况下,num=ran,并将输入初始化为”res”上索引为1的元素。
-
步骤7 – 打印语句将打印替代前后和。
例子
#list is initialized with elements of strings
list_1 = [10, 20, 30, 50]
# variables are Initialized with values
num = 0
ran = len(list_1) - 1
res = []
flag = True
# while loop is used to iterate through the while loop
while num < ran:
if flag:
res.append(list_1[num] + list_1[ran])
flag = False
else:
res.append((list_1[num] + list_1[ran]))
flag = True
num += 1
ran -= 1
# if loop uses the conditional statement to check for odd-numbered list array.
if num == ran:
res.append(list_1[num])
# returns the statement after the front-rear sum
print("Alternating Front-Rear Sum:", *res)
输出
Alternating Front-Rear Sum: 60 50
做法二:使用zip()函数交替求和的Python程序
在下面的代码中,使用zip()函数将列表中的元素从前面和后面组合起来,然后计算交替的前后求和。reversed()函数用于以倒序遍历列表。
算法
- 步骤1 - 初始化列表,设置一组元素。
-
步骤2 - 初始化一个空列表。
-
步骤3 - 设置标志为真,然后使用zip()函数与两个参数列表list_1和reversed list_1一起使用。然后将当前的元素添加到空列表中。
-
步骤4 - 设置标志为假,然后使用zip()函数与两个参数列表list_1和reversed list_1一起使用。然后对当前元素进行负求和。
-
步骤5 - 当列表的长度为奇数时,将中间元素添加到空列表中。
-
步骤6 - 然后打印语句将打印交替的前后求和。
示例
#list is initialized with elements of strings
list_1 = [10, 20, 30, 50]
#initializing the empty list
empty = []
use = []
flag = True
#for loop is used to iterate through the list using the zip function
for a, b in zip(list_1, reversed(list_1)):
if flag:
empty.append(a + b)
flag = False
else:
use.append((a + b))
flag = True
# if loop uses the conditional statement to check for an even numbered list array.
if len(list_1) % 2 != 0:
empty.append(list_1[len(list_1) // 2])
# returns the statement after the front-rear sum
print("Alternating Front-Rear Sum:", *empty)
输出结果
Alternating Front-Rear Sum: 60 50
结论
给定数组元素的计算后和前交替和的Python程序。当数组列表的长度为偶数时,元素的添加更容易,而当列表的长度为奇数时,元素的添加相对困难。最终的数字添加在列表的末尾。