Merging List Lists

I have two lists of lists that have an equivalent number of items. The two lists are as follows:

L1 = [[1, 2], [3, 4], [5, 6, 7]]

L2 =[[a, b], [c, d], [e, f, g]]

I want to create one list that looks like this:

Lmerge = [[[a, 1], [b,2]], [[c,3], [d,4]], [[e,5], [f,6], [g,7]]]

I tried to use map():

map(list.__add__, L1, L2)but the output is a flat list.

What is the best way to combine two lists of lists? Thanks in advance.

+4
source share
2 answers

You can ziplists and then the zipresulting tuples again ...

>>> L1 = [[1, 2], [3, 4], [5, 6, 7]]
>>> L2 =[['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]
>>> [list(zip(a,b)) for a,b in zip(L2, L1)]
[[('a', 1), ('b', 2)], [('c', 3), ('d', 4)], [('e', 5), ('f', 6), ('g', 7)]]

If you need lists in the reverse order, combine them with `map:

>>> [list(map(list, zip(a,b))) for a,b in zip(L2, L1)]
[[['a', 1], ['b', 2]], [['c', 3], ['d', 4]], [['e', 5], ['f', 6], ['g', 7]]]
+7
source

You were on the right track with help map.

tobias_k, zip :

>>> zipped = map(zip, L2, L1)
>>> list(map(list, zipped)) # evaluate to a list of lists
[[('a', 1), ('b', 2)], [('c', 3), ('d', 4)], [('e', 5), ('f', 6), ('g', 7)]]

, Python 2 map(zip, L2, L1).

map(zip, L2, L1) Python 3, , . , itertools.tee.

:

>>> [list(map(list, x)) for x in map(zip, L2, L1)]
[[['a', 1], ['b', 2]], [['c', 3], ['d', 4]], [['e', 5], ['f', 6], ['g', 7]]]

, :

>>> from functools import partial
>>> map(partial(map, list), map(zip, L2, L1))
[[['a', 1], ['b', 2]], [['c', 3], ['d', 4]], [['e', 5], ['f', 6], ['g', 7]]]
+3

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


All Articles