4
a = {2: 4, 3: 2, 5: 1, 7: 1}

键代表素数;这些值代表计数器。我想通过遍历字典键*值并对总数求和来计算你得到的数字。最Pythonic的方法是什么?

>>> [k*v for k,v in a.items()]
[8, 6, 5, 7]

>>> sum(k*v for k,v in a.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
4

2 回答 2

7

这边走:

sum(k*v for k,v in a.items())

或使用语义命名:

sum(p*c for p,c in primesToCounts.items())
于 2012-06-02T21:15:06.220 回答
2

怎么样:

>>> a = {2: 4, 3: 2, 5: 1, 7: 1}
>>> [key * val for key, val in a.items()]
... [8, 6, 5, 7]
>>> sum([key * val for key, val in a.items()])
... 26

这很pythonic。

于 2012-06-02T21:16:00.020 回答