二维数组的python sum如何返回一个列表

Nru*_*esh 2 python arrays sum list

我遇到了一段 python 代码,其中二维数组的 sum 函数计算为一个列表。

例如:

a = [['a','b','c'],['d','e','f'],['g','h','i']]]

sum(a,[]) 返回 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

为什么会发生这种情况?也许我错过了一些基本的东西,但想了解它的机制。

Nic*_*ick 7

sum(iterable, /, start=0)

从左到右对开始和可迭代项的总和并返回总数

所以对于你的代码,产生的操作sum

[] + ['a','b','c'] + ['d','e','f'] + ['g','h','i']
Run Code Online (Sandbox Code Playgroud)

这是一个列表连接,并产生:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
Run Code Online (Sandbox Code Playgroud)

请注意,如果您不提供 的start[], sum 将使用的默认start0并执行:

0 + ['a','b','c'] + ['d','e','f'] + ['g','h','i']
Run Code Online (Sandbox Code Playgroud)

结果是TypeError

类型错误:不支持 + 的操作数类型:'int' 和 'list'