Dictionary 中的 Python-sum 值

我有一个很简单的清单:

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

我如何加总所有的 黄金值? 我正在寻找漂亮的线条。

现在我正在使用这段代码(但它不是最好的解决方案) :

total_gold = 0
for item in example_list:
total_gold += example_list["gold"]
112028 次浏览
sum(item['gold'] for item in myList)

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.

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.

from collections import Counter
from functools import reduce
from operator import add


sum_dict = reduce(add, (map(Counter, example_list)))
# Counter({'points': 700, 'gold': 4330})
total_gold = sum_dict['gold']
example_list = [
{'points': 400, 'gold': 2480},
{'points': 100, 'gold': 610},
{'points': 100, 'gold': 620},
{'points': 100, 'gold': 620}
]


result = np.sum([x['gold'] for x in example_list])




print(result)

output

 4330