在python中使二维数组成为一维

Make 2D array 1-dimensional in Python

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

我试图"展平"一个数组,将其转换为一维的项集。我使用append命令,得到:

1
[['X', 'X'],['ff','ff','ff','ff','ff']]

但我希望元素排序为:

1
['X','X','ff','ff','ff','ff','ff']

我不能使用string.join()或string.split()运算符。那么,执行这一操作最明智的方法是什么呢?


我想你要找的是不是比添加extend()()

1
2
3
4
5
6
7
8
>>> oldList = [['X', 'X'],['ff','ff','ff','ff','ff']]
>>> print oldList
[['X', 'X'], ['ff', 'ff', 'ff', 'ff', 'ff']]
>>> newList = []
>>> for item in oldList:
...     newList.extend( item )
>>> print newList
>>> ['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']

使用列表的理解:

1
2
alist = [['X', 'X'],['ff','ff','ff','ff','ff']]
print [j for i in alist for j in i ]

使用:减少

1
reduce(lambda r,x:r+x, alist,[])

输出:

1
['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']


使用itertools.chainextend()

1
2
3
4
5
6
7
8
9
>>> from itertools import chain
>>> oldList = [['X', 'X'],['ff','ff','ff','ff','ff']]
>>> list(chain.from_iterable(oldList))
['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']

>>> list1 = ['X', 'X']
>>> list1.extend(['ff','ff','ff','ff','ff'])
>>> list1
['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']


学院有"清酒性,永远是

1
2
3
In [1]: x = [['X', 'X'], ['ff', 'ff', 'ff', 'ff', 'ff']]
In [2]: sum(x, [])
Out[2]: ['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']

1
2
In [3]: [item for sublist in x for item in sublist]
Out[3]: ['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']

要的速度,和

1
2
3
In [4]: from itertools import chain
In [5]: list(chain.from_iterable(x))
Out[5]: ['X', 'X', 'ff', 'ff', 'ff', 'ff', 'ff']

应该是最快的。