假设我有一个字典,其中键映射到像这样的整数:
d = {'key1': 1,'key2': 14,'key3': 47}
是否有一种语法上最简单的方法来返回d中值的和,即。62个吗?
假设我有一个字典,其中键映射到像这样的整数:
d = {'key1': 1,'key2': 14,'key3': 47}
是否有一种语法上最简单的方法来返回d中值的和,即。62个吗?
当前回答
简单/荒谬的解决方案:
https://trinket.io/python/a8a1f25353
d = {'key1': 1,'key2': 14,'key3': 47}
s = 0
for k in d:
s += d[k]
print(s)
或者如果你想让它更花哨:
https://trinket.io/python/5fcd379536
import functools
d = {'key1': 1,'key2': 14,'key3': 47}
s = functools.reduce(lambda acc,k: acc+d[k], d, 0)
print(s)
其他回答
如你所料:
sum(d.values())
d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)
print(sum1)
你可以使用for循环来实现
简单/荒谬的解决方案:
https://trinket.io/python/a8a1f25353
d = {'key1': 1,'key2': 14,'key3': 47}
s = 0
for k in d:
s += d[k]
print(s)
或者如果你想让它更花哨:
https://trinket.io/python/5fcd379536
import functools
d = {'key1': 1,'key2': 14,'key3': 47}
s = functools.reduce(lambda acc,k: acc+d[k], d, 0)
print(s)
您可以获得字典中所有值的生成器,然后将其转换为一个列表,并使用sum()函数获得所有值的和。
例子:
c={"a":123,"b":4,"d":4,"c":-1001,"x":2002,"y":1001}
sum(list(c.values()))
总和(d.值())
"d" ->你的字典变量