给定这样的设置:
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/