📜  Python|元组列表中的累积索引求和

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

Python|元组列表中的累积索引求和

有时,在处理数据时,我们可能会遇到需要找到元组中每个索引的累积和的问题。这个问题可以在 Web 开发和竞争性编程领域中得到应用。让我们讨论一下可以解决这个问题的某种方法。

方法:使用accumulate() + sum() + lambda + map() + tuple() + zip()
上述功能的组合可以用来解决这个任务。在此,我们使用zip()对元素进行配对,然后对它们求和,然后使用map()将其扩展到所有元素。 sum 的取值是通过使用累积来完成的。所有逻辑的绑定都是由 lambda 函数完成的。

# Python3 code to demonstrate working of
# Accumulative index summation in tuple list
# Using accumulate() + sum() + lambda + map() + tuple() + zip()
from itertools import accumulate
  
# initialize list
test_list = [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Accumulative index summation in tuple list
# Using accumulate() + sum() + lambda + map() + tuple() + zip()
res = list(accumulate(test_list, lambda i, j: tuple(map(sum, zip(i, j)))))
  
# printing result
print("Accumulative index summation of tuple list : " + str(res))
输出 :
The original list : [(3, 4, 5), (4, 5, 7), (1, 4, 10)]
Accumulative index summation of tuple list : [(3, 4, 5), (7, 9, 12), (8, 13, 22)]