📜  Python|元组列表第K列的求和

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

Python|元组列表第K列的求和

有时,在使用Python列表时,我们可能会有一个任务,我们需要使用元组列表并获得它的第 K 个索引的可能累积。在处理数据信息时,此问题在 Web 开发领域有应用。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + sum()
可以使用上述功能的组合来执行此任务。在这种情况下,使用sum()进行索引求和,列表理解驱动列表中每个元组的第 N 个索引元素的迭代和访问。

# Python3 code to demonstrate working of
# Summation of Kth Column of Tuple List
# using list comprehension + sum()
  
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initialize K
K = 2
  
# Summation of Kth Column of Tuple List
# using list comprehension + sum()
res = sum([sub[K] for sub in test_list])
  
# printing result
print("Summation of Kth Column of Tuple List : " + str(res))
输出 :
The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Summation of Kth Column of Tuple List : 31

方法#2:使用imap() + sum() + itemgetter()
以上功能的组合也可以完成这个任务。这种方法是基于生成器的,建议在我们有一个非常大的列表的情况下使用。其中sum()用于执行求和,itemgetter 获取第 K 个索引, imap()执行映射元素的任务以执行求和。仅适用于 Python2。

# Python code to demonstrate working of
# Summation of Kth Column of Tuple List
# using imap() + sum() + itemgetter()
from operator import itemgetter
from itertools import imap
  
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initialize K
K = 2
  
# Summation of Kth Column of Tuple List
# using imap() + sum() + itemgetter()
idx = itemgetter(K)
res = sum(imap(idx, test_list))
  
# printing result
print("Summation of Kth Column of Tuple List : " + str(res))
输出 :
The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Summation of Kth Column of Tuple List : 31