python list分组_Python列表分组和总和

本文介绍了一种使用Python的collections.Counter模块来汇总列表中重复项的方法。针对包含姓名和计数的字典列表,通过遍历列表并将每个条目的计数累加到对应姓名的总和上,实现了对相同姓名下计数的求和操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Suppose I have the following list:

[{'name': 'Amy', 'count': 1}, {'name': 'Amy', 'count': 2}, {'name': 'Peter', 'count': 1}]

How could I group it and sum the count in order to get the following out:

[{'name': 'Amy', 'count': 3}, {'name': 'Peter', 'count': 1}]

Thanks.

解决方案

You can use a collecions.Counter:

from collections import Counter

l = [

{'name': 'Amy', 'count': 1},

{'name': 'Amy', 'count': 2},

{'name': 'Peter', 'count': 1}

]

c = Counter()

for v in l:

c[v['name']] += v['count']

Result:

>>> c

Counter({'Amy': 3, 'Peter': 1})

>>> [{'name': name, 'count': count} for name, count in c.items()]

[{'count': 3, 'name': 'Amy'}, {'count': 1, 'name': 'Peter'}]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值