Python - 对字典中的值求和

101
我有一个非常简单的列表:
example_list = [
    {'points': 400, 'gold': 2480},
    {'points': 100, 'gold': 610},
    {'points': 100, 'gold': 620},
    {'points': 100, 'gold': 620}
]

如何对所有的gold值求和?我正在寻找优美的一行代码。

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

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

6
不应该使用“list”作为局部变量的名称,这样会掩盖内置的“list”类型并可能引起问题。 - g.d.d.c
2
你说得对,我只是为了这个例子而使用它。 - Mateusz Jagiełło
@sigo -- 在这种情况下,有一个漂亮的一行代码,但通常,将答案限制为“漂亮的一行代码”可能是一个坏主意(因为可能存在更好的多行代码)。 - mgilson
5个回答

222
sum(item['gold'] for item in myList)

30

如果你注重内存:

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

如果您非常注重时间:

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

在大多数情况下,只需使用生成器表达式即可,因为性能提升只在非常大的数据集/非常热的代码路径上才会明显。

请参见此答案,了解应避免使用map的原因。

请参见此答案,了解列表推导与生成器表达式在实际运行时间的比较。


为什么类似 sum(item.gold for item in example_list) 的语句不能正常工作?我得到了一个 AttributeError: 'dict' object has no attribute 'gold' 的错误。 - cryanbhu
2
因为字典类型没有名为“gold”的属性(类型成员)。你可能把Python和JavaScript搞混了。在JS中,您可以使用点表示法或索引表示法,因为那里的类似字典的对象通常只是普通的JS对象。在Python中,字典就是字典,必须使用索引运算符,所以长话短说:您需要使用item['gold']而不是item.gold - Ben Burns

8
如果您更喜欢使用“map”函数,也可以这样写:

map函数的示例:

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

但我认为g.d.d.c发布的生成器更好。这个答案只是为了指出operator.itemgetter的存在。

5
_reduce = lambda fn, ar: fn(ar[0], _reduce(fn, ar[1:])) if len(ar) > 1 else ar[0] total_gold = _reduce((lambda x, y: x + y), (lambda fn, ar: [fn(ar[i]) for i in range(len(ar))])((lambda x: x["gold"]), example_list)) - Moop
1
感谢--注释格式似乎不尊重换行,所以看起来比实际更糟糕。 - Moop
@Filipq -- 真的,我在g.d.d.c之后大约30秒发布了相同的答案。我最初删除了它,但自从我得到了愚蠢的版主工具以来,我仍然可以看到我的已删除答案。这让我感到烦恼,所以我想,一定有另一种比较干净的方法来做这件事,可以说明一些有用的东西...不过我可能应该把它删除...我不知道。(我愿意听取建议)。 - mgilson

5
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']

很好,这允许在不必知道所有键的情况下计算字典中任意项(例如,这将支持一次性计算字典中的所有键而无需指定它们)。 - mdmjsh

0
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)

输出

 4330

这与使用非 np 的 sum 不同吗? - General Grievance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接