Python|两个元组列表的总和
有时,在处理Python记录时,我们可能会遇到需要对元组列表执行交叉求和的问题。这种应用程序在Web开发领域很流行。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + zip()
上述功能的组合可用于执行此特定任务。在此,我们使用列表推导遍历列表,并在zip()
的帮助下执行跨列表的求和。
# Python3 code to demonstrate working of
# Summation of two list of tuples
# using list comprehension + zip()
# initialize lists
test_list1 = [(2, 4), (6, 7), (5, 1)]
test_list2 = [(5, 4), (8, 10), (8, 14)]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# Summation of two list of tuples
# using list comprehension + zip()
res = [(x[0] + y[0], x[1] + y[1]) for x, y in zip(test_list1, test_list2)]
# printing result
print("The Summation across lists is : " + str(res))
输出 :
The original list 1 : [(2, 4), (6, 7), (5, 1)]
The original list 2 : [(5, 4), (8, 10), (8, 14)]
The Summation across lists is : [(7, 8), (14, 17), (13, 15)]
方法#2:使用sum() + zip() + map()
这是执行此任务的另一种方式。这与上述方法类似,不同之处在于求和是由内置函数执行的,而对每个元素的逻辑扩展是由map()
完成的。
# Python3 code to demonstrate working of
# Summation of two list of tuples
# using sum() + zip() + map()
# initialize lists
test_list1 = [(2, 4), (6, 7), (5, 1)]
test_list2 = [(5, 4), (8, 10), (8, 14)]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# Summation of two list of tuples
# using sum() + zip() + map()
res = [tuple(map(sum, zip(a, b))) for a, b in zip(test_list1, test_list2)]
# printing result
print("The Summation across lists is : " + str(res))
输出 :
The original list 1 : [(2, 4), (6, 7), (5, 1)]
The original list 2 : [(5, 4), (8, 10), (8, 14)]
The Summation across lists is : [(7, 8), (14, 17), (13, 15)]