Python|列表中元组的总和
有时,在处理记录时,我们可能会遇到一个问题,即我们需要找到元组中存在的所有值的累积和。这可以在我们处理大量记录数据的情况下应用。让我们讨论一些可以解决这个问题的方法。
方法#1:使用 sum() + map()
上述功能的组合可用于解决此特定问题。在此,求和任务由 sum() 执行,而对元组列表中的每个元素应用求和功能由 map() 执行。
Python3
# Python3 code to demonstrate working of
# Summation of tuples in list
# using sum() + map()
# initialize list of tuple
test_list = [(1, 3), (5, 6, 7), (2, 6)]
# printing original tuples list
print("The original list : " + str(test_list))
# Summation of tuples in list
# using sum() + map()
res = sum(map(sum, test_list))
# printing result
print("The summation of all tuple elements are : " + str(res))
Python3
# Python3 code to demonstrate working of
# Summation of tuples in list
# using sum() + izip()
from itertools import izip
# initialize list of tuple
test_list = [(1, ), (5, ), (2, )]
# printing original tuples list
print("The original list : " + str(test_list))
# Summation of tuples in list
# using sum() + map()
res = sum(*izip(*test_list))
# printing result
print("The summation of all tuple elements are : " + str(res))
输出 :
The original list : [(1, 3), (5, 6, 7), (2, 6)]
The summation of all tuple elements are : 30
方法#2:使用 sum() + izip()
上述功能的组合可用于执行此特定任务。在此,我们使用 izip() 执行 map() 的任务。它有助于通过 sum() 对所有元素进行求和。仅适用于单元素元组且仅适用于 Python2。
Python3
# Python3 code to demonstrate working of
# Summation of tuples in list
# using sum() + izip()
from itertools import izip
# initialize list of tuple
test_list = [(1, ), (5, ), (2, )]
# printing original tuples list
print("The original list : " + str(test_list))
# Summation of tuples in list
# using sum() + map()
res = sum(*izip(*test_list))
# printing result
print("The summation of all tuple elements are : " + str(res))
输出 :
The original list : [(1, ), (5, ), (2, )]
The summation of all tuple elements are : 8