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,并将输入中索引 1 处的元素初始化到 res 中。
步骤 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
方法 2:使用 zip() 函数的 Python 程序来计算交替前后求和
在下面的代码中,zip() 函数用于组合列表中来自前后端的元素,然后计算交替前后求和。reversed() 函数用于以相反的顺序遍历列表。
算法
步骤 1 − 使用一组元素初始化列表。
步骤 2 − 然后初始化空列表。
步骤 3 − 标志为真,然后使用 zip() 函数以及两个参数,即 list_1 和反转的 list_1。然后将当前元素添加到空列表中。
步骤 4 − 标志为假,然后使用 zip() 函数以及两个参数,即 list_1 和反转的 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 程序,用于计算给定元素数组的后端和前端交替求和。对于数组列表的偶数长度,元素的加法更容易,另一方面,当元素具有奇数长度的列表时。最终数字添加到列表的末尾。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP