Merge multiple 2d lists considering axis in order

最后都变了- 提交于 2019-12-01 06:34:32

You can use zip and a list comprehension:

>>> a = [[1,2],[3,1]]
>>> b = [[3,6],[2,9]]
>>> c = [[5,1],[8,10]]
>>> [x+y+z for x,y,z in zip(a, b, c)]
[[1, 2, 3, 6, 5, 1], [3, 1, 2, 9, 8, 10]]
>>>

You could use itertools.chain.from_iterable():

>>> a = [[1, 2], [3, 1]]
>>> b = [[3, 6], [2, 9]]
>>> c = [[5, 1], [8, 10]]
>>> from itertools import chain
>>> [list(chain.from_iterable(x)) for x in zip(a, b, c)]
[[1, 2, 3, 6, 5, 1], [3, 1, 2, 9, 8, 10]]

This might be handy if you have an arbitrary number of 2D lists - for example:

>>> list_of_lists = [
...     [[1, 2], [3, 1]],
...     [[3, 6], [2, 9]],
...     [[5, 1], [8, 10]],
...     # ...
...     [[4, 7], [11, 12]]
... ]
>>> [list(chain.from_iterable(x)) for x in zip(*list_of_lists)]
[[1, 2, 3, 6, 5, 1, ..., 4, 7], [3, 1, 2, 9, 8, 10, ..., 11, 12]]

Note the * before list_of_lists in this last example, which is an example of argument unpacking.

This might be another solution using numpy but this is much slower.

import numpy as np

a = [[1,2],[3,1]]
b = [[3,6],[2,9]]
c = [[5,1],[8,10]]

print np.hstack((np.hstack((a,b)),c))

# [[ 1  2  3  6  5  1]
# [ 3  1  2  9  8 10]]

and if you want it to have a list format then use

np.hstack((np.hstack((a,b)),c)).tolist()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!