how to add all array's elements to one list in python
本问题已经有最佳答案,请猛点这里访问。
使用类似于此的二维数组:
1 | myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']] |
每个元素都是一个具有固定长度元素的数组。如何成为这个人,
1 | mylist = ['jacob','mary','jack','white','fantasy','clothes','heat','abc','edf','fgc'] |
这是我的解决方法
1 2 3 | mylist = [] for x in myarray: mylist.extend(x) |
我想应该更简单些
使用
1 2 | from itertools import chain mylist = list(chain.from_iterable(myarray)) |
演示:
1 2 3 4 | >>> 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解决方案是为您的
1 2 3 4 5 6 | >>> 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 |
但是,如果输入
1 2 3 4 5 6 7 | >>> 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 2 3 | >>> myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']] >>> sum(myarray,[]) ['jacob', 'mary', 'jack', 'white', 'fantasy', 'clothes', 'heat', 'abc', 'edf', 'fgc'] |
或
1 2 | >>> [i for j in myarray for i in j] ['jacob', 'mary', 'jack', 'white', 'fantasy', 'clothes', 'heat', 'abc', 'edf', 'fgc'] |