[英]Python - sum values in dictionary
我有一个非常简单的列表:
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"]
sum(item['gold'] for item in myList)
如果您更喜欢map
,这也适用:
import operator
total_gold = sum(map(operator.itemgetter('gold'),example_list))
但我认为 gddc 发布的生成器要好得多。 这个答案实际上只是为了指出operator.itemgetter
的存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.