Merge of several 2 lists taking into account the axis in order

My goal is to combine a few 2nd list in such a way as:

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

Following other tips from this site, I tried to use the collections module, for example, the code below:

from collections import Counter
a = [[1,2],[3,1]]
b= [[3,6],[2,9]]
c = [[5,1],[8,10]]
d = [[k,v] for k,v in (Counter(dict(a)) + Counter(dict(b))+ Counter(dict(c))).items()]
print d

However, a result [[1, 2], [3, 1], [3, 6], [2, 9]]that is not as expected.

Do you have an idea to solve this problem? Perhaps if there is a function or module to consider an axis for combining lists.

+4
source share
3 answers

You can use zipand a list of :

>>> 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]]
>>>
+8
source

You can 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]]

, 2D- - :

>>> 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]]

* list_of_lists , .

+6

It may be another solution using numpy, but it 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, use

np.hstack((np.hstack((a,b)),c)).tolist()
+1
source

Source: https://habr.com/ru/post/1542584/


All Articles