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
最佳答案
这样:
sum(k*v for k,v in a.items())
或使用语义命名:
sum(p*c for p,c in primesToCounts.items())
关于python - 在字典中乘以键*值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865979/