为什么 sum 函数的参数需要在括号中?

Tre*_*vor 1 python

为什么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))
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*uck 6

这是因为 python 内置函数 sum() 接受一个可迭代的参数和可迭代中起始位置的第二个参数。总和(可迭代[,开始])

这就是为什么添加 3 个参数会给你一个错误。您可以在文档中阅读更多内容:https : //docs.python.org/2/library/functions.html#sum

max() 另一方面接受不同的参数, max(iterable[, key]) 和 max(arg1, arg2, *args[, key]) 如https://docs.python.org/2/library/ functions.html#max 它可以接受一个可迭代的或一堆数字作为参数并返回最大值。