Merging Lists Of Lists
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 crea
Solution 1:
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]]]
Solution 2:
You were on the right track with the map
.
Here's a shorter alternative to the first version by tobias_k, zip
together corresponding elements from both lists:
>>> 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)]]
As noted in the comments, in Python 2, the brief map(zip, L2, L1)
is enough.
map(zip, L2, L1)
will work for you in Python 3 too, given that you iterate over it just once and that you don't need sequence access by index. And if you need to iterate many times, you may be interested in itertools.tee
.
A shorter alternative to the second version:
>>> [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]]]
Lastly, there's also this:
>>> 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]]]
Post a Comment for "Merging Lists Of Lists"