a = {2: 4, 3: 2, 5: 1, 7: 1}
键代表素数;值代表计数器。我想通过迭代字典键*值并总计总和来计算得到的数字。最恐怖的方式是什么?
>>> [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
答案 0 :(得分:4)
这样:
sum(k*v for k,v in a.items())
或使用语义命名:
sum(p*c for p,c in primesToCounts.items())
答案 1 :(得分: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。