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.
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]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With