Python中元组列表的分组求和!
当需要找到元组列表的分组总和时,需要使用'Counter'方法和'+'运算符。
'Counter'是一个帮助计算可散列对象的子类,i.e它在被调用时自行创建一个散列表(一个可迭代的,如列表、元组等)。
它为所有具有非零值作为计数的元素返回一个itertool。
'+'运算符可用于添加数值或连接字符串。
以下是相同的演示-
示例
from collections import Counter my_list_1 = [('Hi', 14), ('there', 16), ('Jane', 28)] my_list_2 = [('Jane', 12), ('Hi', 4), ('there', 21)] print("Thefirstlistis: ") print(my_list_1) print("Thesecondlistis: " ) print(my_list_2) cumulative_val_1 = Counter(dict(my_list_1)) cumulative_val_2 = Counter(dict(my_list_2)) cumulative_val_3 = cumulative_val_1 + cumulative_val_2 my_result = list(cumulative_val_3.items()) print("Thegroupedsummationoflistoftupleis: ") print(my_result)输出结果
Thefirstlistis: [('Hi', 14), ('there', 16), ('Jane', 28)] Thesecondlistis: [('Jane', 12), ('Hi', 4), ('there', 21)] Thegroupedsummationoflistoftupleis: [('Hi', 18), ('there', 37), ('Jane', 40)]
解释
导入所需的包。
定义了两个元组列表,并显示在控制台上。
这两个元组列表都被转换为字典。
它们是使用“+”运算符添加的。
仅使用字典的“值”将此结果转换为列表。
此操作的数据存储在变量中。
此变量是显示在控制台上的输出。