8

Of course I get it you use sum() with several numbers, then it sums it all up, but I was viewing the documentation on it and I found this:

sum(iterable[, start])

What is that second argument "[, start]" for? This is so embarrasing, but I cannot seem to find any examples with google and the documentation is fairly cryptic for someone who tries to learn the language.

Is it a list of some sort? I cannot get it to work. Here is an example of one of my attempts:

>>> sum(13,4,5,6,[2,4,6])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum expected at most 2 arguments, got 5
4

2 回答 2

11

start 表示总和的起始值,您可以将其等同起来:

sum(iterable, start)

有了这个:

start + sum(iterable)

你的错误的原因是你没有将数字封装在一个迭代中,而是这样做:

sum([13, 4, 5, 6])

这将产生28(13+4+5+6) 的值。如果你这样做:

sum([13, 4, 5, 6], 25)

53相反,您得到(13+4+5+6 + 25)。

于 2013-07-15T23:53:13.440 回答
1

另外,请记住,如果您创建一个嵌套列表(就像您上面的排序一样) sum 会给您一个错误(尝试将整数添加到列表中,不清楚 - 您是在尝试追加还是添加到列表的总和还是什么?)。所以会尝试使用两个列表,+ 被重载并且通常会将两个列表连接成一个,但是 sum 会尝试添加一些东西,所以不清楚你在问什么。

用例子更容易解释:

>>> mylist = [13, 4, 5, 6, [2,4,6]]
>>> sum(mylist)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> a = [13, 4, 5, 6]
>>> b = [2,4,6]
>>> c = [a,b]
>>> c
[[13, 4, 5, 6], [2, 4, 6]]
>>> sum(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> c = a+b
>>> c
[13, 4, 5, 6, 2, 4, 6]
>>> sum(c)
40
>>> sum(c, 23)
63

希望这可以帮助。

于 2013-07-16T00:35:38.477 回答