如何在python中将所有数组元素添加到一个列表中

时间:2013-05-01 10:44:42

标签: python python-3.x

带有2维数组,看起来像这样:

myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']]

每个元素都是一个具有固定长度元素的数组。如何成为这个,

mylist = ['jacob','mary','jack','white','fantasy','clothes','heat','abc','edf','fgc']

这是我的解决方案

mylist = []
for x in myarray:
   mylist.extend(x)

我应该更简单

2 个答案:

答案 0 :(得分:8)

使用itertools.chain.from_iterable

from itertools import chain
mylist = list(chain.from_iterable(myarray))

演示:

>>> from itertools import chain
>>> myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']]
>>> list(chain.from_iterable(myarray))
['jacob', 'mary', 'jack', 'white', 'fantasy', 'clothes', 'heat', 'abc', 'edf', 'fgc']

但是,Haidro's sum() solution对于较短的样本来说速度更快:

>>> timeit.timeit('f()', 'from __main__ import withchain as f')
2.858742465992691
>>> timeit.timeit('f()', 'from __main__ import withsum as f')
1.6423718839942012
>>> timeit.timeit('f()', 'from __main__ import withlistcomp as f')
2.0854451240156777

但如果输入变大,itertools.chain会获胜:

>>> myarray *= 100
>>> timeit.timeit('f()', 'from __main__ import withchain as f', number=25000)
1.6583486960153095
>>> timeit.timeit('f()', 'from __main__ import withsum as f', number=25000)
23.100156371016055
>>> timeit.timeit('f()', 'from __main__ import withlistcomp as f', number=25000)
2.093297885992797

答案 1 :(得分:5)

>>> myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']]
>>> sum(myarray,[])
['jacob', 'mary', 'jack', 'white', 'fantasy', 'clothes', 'heat', 'abc', 'edf', 'fgc']

或者

>>> [i for j in myarray for i in j]
['jacob', 'mary', 'jack', 'white', 'fantasy', 'clothes', 'heat', 'abc', 'edf', 'fgc']