如何使用sum(iterable,[])展平嵌套列表?

问题描述:

我正在使用python 3.6.我遇到了以下使用sum展平嵌套列表的方法:

I'm using python 3.6. I came across the below way to flatten the nested list using sum:

a = [[1, 2], [3, 4], [5, 6]]

sum(a,[])

返回:

[1,2,3,4,5,6]


这到底是怎么回事? Sum需要一个可迭代的对象(在这种情况下为列表)和一个起始值.我不明白python读取的是什么来弄平列表.


What exactly is going on here? Sum takes an iterable, in this case a list, and a start value. I don't understand what python reads to flatten the list.

这仅仅是Python解释列表添加方式的结果.从文档

This is just a result of how Python interprets addition of lists. From the docs

sum(iterable[, start])

总和从左到右开始,然后是一个可迭代项,然后返回总计.

Sums start and the items of an iterable from left to right and returns the total.

由于sum首先将iterable的第一个元素添加到start参数,所以您具有:

Since sum starts by adding the first element of the iterable to the start argument, you have:

[] + [1, 2] = [1, 2]

然后,它继续从可迭代对象中添加项目:

Then it continues adding items from the iterable:

[1, 2] + [3, 4] = [1, 2, 3, 4]
[1, 2, 3, 4] + [5, 6] = [1, 2, 3, 4, 5, 6]