3

这是与python语法相关的问题......有没有更优雅更pythonic的方式来做到这一点:

>>> test = [[1,2], [3,4,5], [1,2,3,4,5,6]]
>>> result = []
>>> for i in test: result += i
>>> result
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]

将多个列表(存储在另一个列表中)加入一个长列表?

4

1 回答 1

8

使用itertools.chain.from_iterable()类方法:

from itertools import chain

result = list(chain.from_iterable(test))

如果您需要做的只是遍历链表,则不要将其具体化为 a list(),只需循环:

for elem in chain.from_iterable(test):
    print(elem, end=' ')   # prints 1 2 3 4 5 1 2 3 4 5 6

您也可以直接使用参数解包itertools.chain

for elem in chain(*test):

但仅对较小的列表执行此操作。

于 2013-04-20T18:01:06.293 回答