Possible Duplicate:
Making a flat list out of list of lists in Python可能重复:在Python中列出列表列表中的平面列表
I am trying to find an easy way to turn a multi dimensional (nested) python list into a single list, that contains all the elements of sub lists.
我试图找到一种简单的方法将多维(嵌套)python列表转换为单个列表,其中包含子列表的所有元素。
For example:
例如:
A = [[1,2,3,4,5]]
turns to
转向
A = [1,2,3,4,5]
or
要么
A = [[1,2], [3,4]]
turns to
转向
A = [1,2,3,4]
4 个解决方案
#1
22
Use itertools.chain:
使用itertools.chain:
itertools.chain(*iterables)
: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.
创建一个迭代器,它返回第一个迭代中的元素,直到它耗尽,然后进入下一个迭代,直到所有的迭代都用完为止。用于将连续序列作为单个序列处理。
例:
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))
The output is:
输出是:
[1, 2, 3, 4]
[1, 2, 3, 4]
#2
16
Use reduce
function
使用reduce功能
reduce(lambda x, y: x + y, A, [])
Or sum
或者总结
sum(A, [])
#3
5
the first case can also be easily done as:
第一种情况也可以轻松完成:
A=A[0]
#4
3
itertools
provides the chain function for that:
itertools为其提供链函数:
From http://docs.python.org/library/itertools.html#recipes:
来自http://docs.python.org/library/itertools.html#recipes:
def flatten(listOfLists):
"Flatten one level of nesting"
return chain.from_iterable(listOfLists)
Note that the result is an iterable, so you may need list(flatten(...))
.
请注意,结果是可迭代的,因此您可能需要列表(flatten(...))。
#1
22
Use itertools.chain:
使用itertools.chain:
itertools.chain(*iterables)
: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.
创建一个迭代器,它返回第一个迭代中的元素,直到它耗尽,然后进入下一个迭代,直到所有的迭代都用完为止。用于将连续序列作为单个序列处理。
例:
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))
The output is:
输出是:
[1, 2, 3, 4]
[1, 2, 3, 4]
#2
16
Use reduce
function
使用reduce功能
reduce(lambda x, y: x + y, A, [])
Or sum
或者总结
sum(A, [])
#3
5
the first case can also be easily done as:
第一种情况也可以轻松完成:
A=A[0]
#4
3
itertools
provides the chain function for that:
itertools为其提供链函数:
From http://docs.python.org/library/itertools.html#recipes:
来自http://docs.python.org/library/itertools.html#recipes:
def flatten(listOfLists):
"Flatten one level of nesting"
return chain.from_iterable(listOfLists)
Note that the result is an iterable, so you may need list(flatten(...))
.
请注意,结果是可迭代的,因此您可能需要列表(flatten(...))。