将字典中的值相加时出错

Ale*_*der 1 python

尝试对字典中的值求和时,出现以下错误.我希望得到总和(即15),但会引发错误.

这是一个错误吗?

IPython QtConsole 3.1.0 Python 2.7.10 | Continuum Analytics,Inc.| (默认,2015年5月28日,17:04:42)

d = {'1': 1, '2': 2 , '3': 3, '4': 4, '5': 5}

>>> sum(d.values())
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-36-4babd535f17a> in <module>()
----> 1 sum(d.values())

TypeError: 'int' object is not callable
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 5

您已sum在代码中命名了一个指向int 的变量,因此您实际上是在尝试调用而不是sum函数.只需添加一个del sum然后再次尝试代码.一个很好的例子,为什么你不应该影响内置函数名称.

In [24]: sum = 4    
In [25]: sum((1,2))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-a2ca1bd9c959> in <module>()
----> 1 sum((1,2))

TypeError: 'int' object is not callable  
In [26]: del sum
In [27]: sum((1,2))
Out[27]: 3
Run Code Online (Sandbox Code Playgroud)