我试图理解内置sum()函数的工作,但是,start参数已经让我不知所措:
a=[[1, 20], [2, 3]]
b=[[[[[[1], 2], 3], 4], 5], 6]
>>> sum(b,a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> sum(a,b)
[[[[[[1], 2], 3], 4], 5], 6, 1, 20, 2, 3]
Run Code Online (Sandbox Code Playgroud)>>> a=[1,2]
>>> b=[3,4]
>>> sum(a,b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> sum(b,a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
Run Code Online (Sandbox Code Playgroud)我只是傻眼了,不知道发生了什么.以下是python文档所说的内容:http://docs.python.org/library/functions.html#sum.这没有给出'如果开始不是字符串而不是整数怎么办?'的解释?
Win*_*ert 17
Sum做了这样的事情
def sum(values, start = 0):
total = start
for value in values:
total = total + value
return total
Run Code Online (Sandbox Code Playgroud)
sum([1,2],[3,4])扩展类似的东西[3,4] + 1 + 2,您可以看到尝试一起添加数字和列表.
为了使用sum生成列表,值应该是列表列表,而start可以只是一个列表.您将在失败的示例中看到该列表至少包含一些整数,而不是所有列表.
通常情况下,您可能会考虑将sum与list一起使用,即将列表列表转换为列表
sum([[1,2],[3,4]], []) == [1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
但实际上你不应该这样做,因为它会很慢.
a=[[1, 20], [2, 3]]
b=[[[[[[1], 2], 3], 4], 5], 6]
sum(b, a)
Run Code Online (Sandbox Code Playgroud)
此错误与 start 参数无关。列表中有两个项目b。其中一个是[[[[[1], 2], 3], 4], 5],另一个是6,并且一个 list 和 int 不能相加。
sum(a, b)
Run Code Online (Sandbox Code Playgroud)
这是添加:
[[[[[[1], 2], 3], 4], 5], 6] + [1, 20] + [2, 3]
Run Code Online (Sandbox Code Playgroud)
哪个工作正常(因为您只是将列表添加到列表中)。
a=[1,2]
b=[3,4]
sum(a,b)
Run Code Online (Sandbox Code Playgroud)
这是试图添加[3,4] + 1 + 2,这又是不可能的。同样,sum(b,a)正在添加[1, 2] + 3 + 4.
如果开始不是字符串而不是整数怎么办?
sum不能对字符串求和。看:
>>> sum(["a", "b"], "c")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
Run Code Online (Sandbox Code Playgroud)