问题:如何对字典中的所有值求和?
假设我有一本字典,其中的键映射为整数,例如:
d = { 'key1' : 1 , 'key2' : 14 , 'key3' : 47 }
是否有返回值的总和在语法上简约的方式d
-即62
在这种情况下?
Let’s say I have a dictionary in which the keys map to integers like:
d = {'key1': 1,'key2': 14,'key3': 47}
Is there a syntactically minimalistic way to return the sum of the values in d
—i.e. 62
in this case?
回答 0
As you’d expect:
sum(d.values())
回答 1
在Python 2中,您可以避免通过使用itervalues()
dictionary方法创建所有值的临时副本,该方法返回字典键的迭代器:
sum ( d . itervalues ())
在Python 3中,您只能使用d.values()
该方法,因为该方法已更改为可以这样做(并且itervalues()
由于不再需要而被删除)。
为了使编写总是在字典键值上进行迭代的版本无关代码更容易,实用程序功能可能会有所帮助:
import sys
def itervalues ( d ):
return iter ( getattr ( d , ( 'itervalues' , 'values' )[ sys . version_info [ 0 ]> 2 ])())
sum ( itervalues ( d ))
这本质上就是本杰明·彼得森的six
模块所做的。
In Python 2 you can avoid making a temporary copy of all the values by using the itervalues()
dictionary method, which returns an iterator of the dictionary’s keys:
sum(d.itervalues())
In Python 3 you can just use d.values()
because that method was changed to do that (and itervalues()
was removed since it was no longer needed).
To make it easier to write version independent code which always iterates over the values of the dictionary’s keys, a utility function can be helpful:
import sys
def itervalues(d):
return iter(getattr(d, ('itervalues', 'values')[sys.version_info[0]>2])())
sum(itervalues(d))
This is essentially what Benjamin Peterson’s six
module does.
回答 2
当然可以。这是一种汇总字典值的方法。
>>> d = { 'key1' : 1 , 'key2' : 14 , 'key3' : 47 }
>>> sum ( d . values ())
62
Sure there is. Here is a way to sum the values of a dictionary.
>>> d = {'key1':1,'key2':14,'key3':47}
>>> sum(d.values())
62
回答 3
d = { 'key1' : 1 , 'key2' : 14 , 'key3' : 47 }
sum1 = sum ( d [ item ] for item in d )
print ( sum1 )
你可以使用for循环
d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)
print(sum1)
you can do it using the for loop
回答 4
我觉得这sum(d.values())
是获得总和的最有效方法。
您也可以尝试用reduce函数来计算总和以及lambda表达式:
reduce ( lambda x , y : x + y , d . values ())
I feel sum(d.values())
is the most efficient way to get the sum.
You can also try the reduce function to calculate the sum along with a lambda expression:
reduce(lambda x,y:x+y,d.values())
回答 5
sum(d.values())-“ d”->您的字典变量
sum(d.values()) – “d” -> Your dictionary Variable
回答 6
phihag的答案(和类似的答案)在python3中不起作用。
对于python 3:
d = { 'key1' : 1 , 'key2' : 14 , 'key3' : 47 }
sum ( list ( d . values ()))
更新!有人抱怨说这行不通!我只是在终端上附上截图。可能是版本不匹配等。
phihag’s answer (and similar ones) won’t work in python3.
For python 3:
d = {'key1': 1,'key2': 14,'key3': 47}
sum(list(d.values()))
Update!
There are complains that it doesn’t work! I just attach a screenshot from my terminal. Could be some mismatch in versions etc.
回答 7
您可以为此考虑“ for循环”:
d = { 'data' : 100 , 'data2' : 200 , 'data3' : 500 }
total = 0
for i in d . values ():
total += i
总计= 800
You could consider ‘for loop’ for this:
d = {'data': 100, 'data2': 200, 'data3': 500}
total = 0
for i in d.values():
total += i
total = 800
回答 8
您可以获取字典中所有值的生成器,然后将其转换为列表,然后使用sum()函数获取所有值的总和。
例:
c ={ "a" : 123 , "b" : 4 , "d" : 4 , "c" :- 1001 , "x" : 2002 , "y" : 1001 }
sum ( list ( c . values ()))
You can get a generator of all the values in the dictionary, then cast it to a list and use the sum() function to get the sum of all the values.
Example:
c={"a":123,"b":4,"d":4,"c":-1001,"x":2002,"y":1001}
sum(list(c.values()))