如何在Python中对具有相同名称的元组的值求和
- 作者: 长联会灬森蚺
- 来源: 51数据库
- 2022-10-21
问题描述
我有以下列表,其中包含必须值的元组:
I have the following list containing tuples that have to values:
mylist=[(3, 'a'), (2, 'b'), (4, 'a'), (5, 'c'), (2, 'a'), (1, 'b')]
有没有办法对所有同名的值求和?比如:
Is there a way to sum all values that share the same name? Something like:
(9, 'a'), (3, 'b'), (5, 'c')
我尝试使用 for 循环迭代元组,但无法得到我想要的.
I tried iterating tuples with for loop but can't get what i want.
谢谢
推荐答案
你可以使用itertools.groupby(按每个元组的第二个值排序后)创建组.然后对于每个组,对每个元组中的第一个元素求和,然后在列表推导中为每个组创建一个元组.
You can use itertools.groupby (after sorting by the second value of each tuple) to create groups. Then for each group, sum the first element in each tuple, then create a tuple per group in a list comprehension.
>>> import itertools >>> [(sum(i[0] for i in group), key) for key, group in itertools.groupby(sorted(mylist, key = lambda i: i[1]), lambda i: i[1])] [(9, 'a'), (3, 'b'), (5, 'c')]
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
