2016-02-07 44 views
0

爲什麼sum(1,2)導致TypeError: 'int' object is not iterablesum(1,2,3)導致TypeError: sum expected at most 2 arguments, got 3,但如果我添加更多括號可以嗎?爲什麼總和函數的參數需要放在括號內?

sum((1,2,3)) 

同時,max(1,2,3)max((1,2,3))都行。

+0

他們不同的功能,它們接受不同的參數。 [總和需要一個迭代和一個可選的開始值](https://docs.python.org/3/library/functions.html#sum),而[max需要一個迭代或一組值(https:// docs .python.org/3 /庫/ functions.html#最大值)。 – jakevdp

+0

閱讀https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences差異 – Selcuk

+1

@jakevdp你應該做出答案。 – tripleee

回答

1

sum需要一個強制參數,它必須是任何數字序列,即數字的列表或元組(而不是字符串)。

如果給出,可選的第二個參數將被添加到結果中。

>>> sum((1, 2, 3)) 
6 
>>> sum([1, 2, 3]) 
6 
>>> sum((1, 2, 3), 4) 
10 
>>> sum([1, 2, 3], 4) 
10 
3

這是因爲內置函數總和()蟒需要迭代的參數,並開始在迭代位置的第二個參數。 sum(iterable [,start])

這就是添加3個參數給你一個錯誤的原因。你可以在文檔閱讀更多:https://docs.python.org/2/library/functions.html#sum

MAX(),另一方面接受的說法不同,MAX(迭代[,鍵])和 MAX(ARG1,ARG2,* ARGS [,鍵]),如發現https://docs.python.org/2/library/functions.html#max 它可以接受一個迭代或一堆數字作爲參數並返回最大值。 「

0

」從左到右總計開始和可迭代的項目,並返回總數。「
只是爲了你的理智證明這一點,也許爛攤子:

>>> type ((1)) 
<type 'int'> 
>>> sum ((1),2) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'int' object is not iterable 

>>> type ((1,)) 
<type 'tuple'> 
>>> sum ((1,),2) 
3 

>>> type ([1]) 
<type 'list'> 
>>> sum ([1],2) 
3 

>>> type ([1,]) 
<type 'list'> 
>>> sum ([1,],2) 
3 
>>> 
相關問題