Python - sum values in dictionary

為{幸葍}努か 提交于 2019-12-17 07:11:37

问题


I have got pretty simple list:

example_list = [
    {'points': 400, 'gold': 2480},
    {'points': 100, 'gold': 610},
    {'points': 100, 'gold': 620},
    {'points': 100, 'gold': 620}
]

How can I sum all gold values? I'm looking for nice oneliner.

Now I'm using this code (but it's not the best solution):

total_gold = 0
for item in example_list:
    total_gold += example_list["gold"]

回答1:


sum(item['gold'] for item in myLIst)



回答2:


If you're memory conscious:

sum(item['gold'] for item in example_list)

If you're extremely time conscious:

sum([item['gold'] for item in example_list])

In most cases just use the generator expression, as the performance increase is only noticeable on a very large dataset/very hot code path.

See this answer for an explanation of why you should avoid using map.

See this answer for some real-world timing comparisons of list comprehension vs generator expressions.




回答3:


If you prefer map, this works too:

 import operator
 total_gold = sum(map(operator.itemgetter('gold'),example_list))

But I think the generator posted by g.d.d.c is significantly better. This answer is really just to point out the existence of operator.itemgetter.



来源:https://stackoverflow.com/questions/11692613/python-sum-values-in-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!