📜  用于列表中重叠的连续数字总和的Python程序

📅  最后修改于: 2022-05-13 01:55:02.497000             🧑  作者: Mango

用于列表中重叠的连续数字总和的Python程序

给定一个 List,通过重叠对连续元素进行求和。

方法 1:使用列表理解 + zip()

在这里,我们使用 zip() 压缩列表,使用连续元素',然后使用 +运算符执行求和。迭代部分是使用列表理解完成的。

Python3
# initializing list
test_list = [4, 7, 3, 2, 9, 2, 1]
  
# printing original list
print("The original list is : " + str(test_list))
  
# using zip() to get pairing.
# last element is joined with first for pairing
res = [a + b for a, b in zip(test_list, test_list[1:] + [test_list[0]])]
  
# printing result
print("The Consecutive overlapping Summation : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Consecutive overlapping Summation
# Using sum() + list comprehension + zip()
  
# initializing list
test_list = [4, 7, 3, 2, 9, 2, 1]
  
# printing original list
print("The original list is : " + str(test_list))
  
# using sum() to compute elements sum
# last element is joined with first for pairing
res = [sum(sub) for sub in zip(test_list, test_list[1:] + [test_list[0]])]  
  
# printing result 
print("The Consecutive overlapping Summation : " + str(res))


输出
The original list is : [4, 7, 3, 2, 9, 2, 1]
The Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]

方法#2:使用 sum() + 列表推导 + zip()

在此,我们使用 sum() 执行求和任务,并保留与上述方法类似的所有功能。

蟒蛇3

# Python3 code to demonstrate working of 
# Consecutive overlapping Summation
# Using sum() + list comprehension + zip()
  
# initializing list
test_list = [4, 7, 3, 2, 9, 2, 1]
  
# printing original list
print("The original list is : " + str(test_list))
  
# using sum() to compute elements sum
# last element is joined with first for pairing
res = [sum(sub) for sub in zip(test_list, test_list[1:] + [test_list[0]])]  
  
# printing result 
print("The Consecutive overlapping Summation : " + str(res))


输出
The original list is : [4, 7, 3, 2, 9, 2, 1]
The Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]