带有列表参数的 Python sum() 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18730299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python sum() function with list parameter
提问by Ro Mc
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 forloop to add the numbers manually. I thought it would be something simple like the following, but I receive TypeError: 'int' object is not callable.
我需要使用该sum()函数来对列表中的值求和。请注意,这与使用for循环手动添加数字不同。我认为它会像下面这样简单,但我收到TypeError: 'int' object is not callable.
numbers = [1, 2, 3]
numsum = (sum(numbers))
print(numsum)
I looked at a few other solutions that involved setting the start parameter, defining a map, or including forsyntax 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?
我查看了一些其他解决方案,这些解决方案涉及设置 start 参数、定义映射或在 中包含for语法sum(),但我对这些变化没有任何运气,也无法弄清楚发生了什么。有人能给我提供一个最简单的例子来sum()总结一个列表,并解释为什么它是这样完成的吗?
采纳答案by flornquake
Have you used the variable sumanywhere else? That would explain it.
您是否sum在其他任何地方使用过该变量?这样就可以解释了。
>>> 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
The name sumdoesn't point to the function anymore now, it points to an integer.
这个名字sum现在不再指向函数,它指向一个整数。
Solution: Don't call your variable sum, call it totalor something similar.
解决方案:不要调用你的变量sum,调用它total或类似的东西。
回答by jasper
numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)
This would work, if your are trying to Sum up a list.
如果您正在尝试总结一个列表,这将起作用。
回答by Bob McCormick
In the last answer, you don't need to make a list from numbers; it is already a list:
在最后一个答案中,您不需要从数字中列出;它已经是一个列表:
numbers = [1, 2, 3]
numsum = sum(numbers)
print(numsum)

