Python 字典理解从对象求和

标签 python

给定这样的设置:

class Foo():
   state = 'x'
   amount = 1


a = Foo()
b = Foo()
c = Foo()
c.state = 'y'
foos = [a, b, c]

我想获得一个包含键 = object.state、values = sum(object.amounts of objects with that state) 的字典。在这种情况下:

{'x': 2, 'y': 1}

我想自动执行此操作,因此我不需要提前知道不同的可能状态。

当然,我可以像这样以某种无聊的方式进行迭代:

my_dict = {}
for foo in foos:
    try:
        my_dict[foo.state] += foo.value
    except (KeyError, TypeError):
        my_dict[foo.state] = foo.value 

但这有点冗长,我想知道是否有更好的方法来做到这一点,也许是听写理解或其他东西,但到目前为止我的努力是徒劳的。

最佳答案

Counter怎么样? :

>>> from collections import Counter
>>>
>>> foos = [a,b,c]
>>> 
>>> c = Counter()
>>> for x in foos:
        c[x.state] += x.amount


>>> c
Counter({'x': 2, 'y': 1})

关于Python 字典理解从对象求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36249021/

相关文章:

python - 有没有更快的方法来添加两个二维 numpy 数组

python - Django 属性错误 : 'CharField' object has no attribute 'model' after migration

python - 如果出错,如何重试 urlfetch.fetch 几次?

python - 导入错误 : No module named 'PIL' in python 3. 4

python - 为什么 python scrapy 在我的代码中产生重复的项目?

python - pandas 执行 "true"concat

python - ib_insync 减少日志记录的冗长

python - 在字符串中查找数字,加 1 并替换

python - 在 Django/REST 中保存多对多模型?

python - redis python scan_iter 给出不同的键