关于python:如何取消嵌套列表

How to unnest a nested list

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Making a flat list out of list of lists in Python

我试图找到一种简单的方法,将多维(嵌套)python列表转换为包含子列表所有元素的单个列表。

例如:

1
A = [[1,2,3,4,5]]

转向

1
A = [1,2,3,4,5]

1
A = [[1,2], [3,4]]

转向

1
A = [1,2,3,4]


使用itertools.chain:

itertools.chain(*iterables):

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

例子:

1
2
3
4
5
6
7
from itertools import chain

A = [[1,2], [3,4]]

print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))

输出是:

1
2
[1, 2, 3, 4]
[1, 2, 3, 4]


使用reduce功能

1
reduce(lambda x, y: x + y, A, [])

sum

1
sum(A, [])


第一种情况也可以很容易地做到:

1
A=A[0]

itertools提供链功能:

从http://docs.python.org/library/itertools.html食谱:

1
2
3
def flatten(listOfLists):
   "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

请注意,结果是不可数的,因此您可能需要list(flatten(...))