問題描述
我需要使用 sum()
函數來對列表中的值求和.請注意,這與使用 for
循環手動添加數字不同.我以為它會像下面這樣簡單,但我收到 TypeError: 'int' object is not callable
.
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.
解決方案:不要將變量稱為 sum
,將其稱為 total
或類似的名稱.
Solution: Don't call your variable sum
, call it total
or something similar.
這篇關于帶有列表參數的 Python sum() 函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!