带有list参数的Python sum()函数 [英] Python sum() function with list parameter
问题描述
我需要使用sum()函数来对列表中的值求和。请注意,使用'for'循环手动添加数字是DISTINCT。我认为它会像下面这样简单,但我收到'TypeError:'int'对象不可调用'。
I am required to use the sum() function in order to sum the values in a list. Please note that this is DISTINCT from using a 'for' loop to add the numbers manually. I thought it would be something simple like the following, but I receive 'TypeError: 'int' object is not callable'.
numbers = [1, 2, 3]
numsum = (sum(numbers))
print(numsum)
我查看了一些其他涉及设置start参数,定义地图或在sum()中包含'for'语法的解决方案,但我对这些变化没有任何好运,并且无法弄清楚发生了什么。有人可以向我提供sum()的最简单的例子,它会对列表求和,并解释为什么它按照它的方式完成?
I looked at a few other solutions that involved setting the start parameter, defining a map, or including 'for' syntax within sum(), but I haven't had any luck with these variations, and can't figure out what's going on. Could someone provide me with the simplest possible example of sum() that will sum a list, and provide an explanation for why it is done the way it is?
推荐答案
您是否在其他地方使用过变量 sum
?这可以解释它。
Have you used the variable sum
anywhere else? That would explain it.
>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
名称 sum
现在不再指向函数,它指向一个整数。
The name sum
doesn't point to the function anymore now, it points to an integer.
解决方案:不要调用变量总和
,称之为总计
或类似的东西。
Solution: Don't call your variable sum
, call it total
or something similar.
这篇关于带有list参数的Python sum()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!