Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging lists of lists

Tags:

python

merge

list

I have two lists of lists that have equivalent numbers of items. The two lists look like this:

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

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

I am looking to create one list that looks like this:

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

I was attempting to use map() :

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

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

like image 368
user47467 Avatar asked Dec 24 '22 09:12

user47467


1 Answers

You can zip the lists and then zip the resulting 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 all the way down, combine 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]]]
like image 161
tobias_k Avatar answered Jan 08 '23 03:01

tobias_k