Python列表分组和总和 [英] Python list grouping and sum

查看:371
本文介绍了Python列表分组和总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下列表:

[{'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}]

谢谢。

推荐答案

您可以使用 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']

结果:

>>> c
Counter({'Amy': 3, 'Peter': 1})
>>> [{'name': name, 'count': count} for name, count in c.items()]
[{'count': 3, 'name': 'Amy'}, {'count': 1, 'name': 'Peter'}]

这篇关于Python列表分组和总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆