总结列表列表

Dea*_*orn 3 python python-3.x

我在 Python 3.6 中发现了一件奇怪的事情。以下代码返回

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

arr = [1, 2, 3, 4, 5]
print(sum([[i] for i in arr]))
Run Code Online (Sandbox Code Playgroud)

为什么会发生?如何总结列表列表?

jua*_*aga 7

这是来自 REPL 的帮助:

>>> help(sum)
Run Code Online (Sandbox Code Playgroud)
sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.
Run Code Online (Sandbox Code Playgroud)

因此,sum内置start函数返回值的总和,即0,和一个可迭代的numbers。Python 不会事先阻止您滥用函数,它相信您至少正在尝试做正确的事情。当然,如果您碰巧传递了一个列表列表,第一个列表元素将与 相加0,引发:

TypeError: unsupported operand type(s) for +: 'int' and 'list'
Run Code Online (Sandbox Code Playgroud)

事实上,如果你传递一个start参数,一个空列表,在这种情况下,它可以工作:

>>> sum([[e] for e in x], [])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)

然而,这将是低效的。您应该更喜欢[x for sublist in list_of_lists for x in sublist]或任何其他线性时间算法。