Python 中元组列表的分组求和
当需要查找元组列表的分组和时,需要使用“计数器”方法和“+”运算符。
“计数器”是一个有助于对可哈希对象进行计数的子类,即当它被调用时,它会自己创建哈希表(可迭代的对象,如列表、元组等)。
它返回一个迭代工具,用于获取所有非零值的元素作为计数。
“+”运算符可用于添加数字值或连接字符串。
以下是相同的演示 −
示例
from collections import Counter
my_list_1 = [('Hi', 14), ('there', 16), ('Jane', 28)]
my_list_2 = [('Jane', 12), ('Hi', 4), ('there', 21)]
print("The first list is : ")
print(my_list_1)
print("The second list is : " )
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("The grouped summation of list of tuple is : ")
print(my_result)输出
The first list is :
[('Hi', 14), ('there', 16), ('Jane', 28)]
The second list is :
[('Jane', 12), ('Hi', 4), ('there', 21)]
The grouped summation of list of tuple is :
[('Hi', 18), ('there', 37), ('Jane', 40)]说明
- 导入所需的包。
- 定义两个元组列表,并在控制台上显示。
- 这两个元组列表都转换为字典。
- 它们使用“+”运算符进行相加。
- 此结果转换为列表,仅使用字典的“值”。
- 此操作的数据存储在一个变量中。
- 此变量是显示在控制台上的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP