How can I merge these 3 lists in this specific way?
Input:
l1 = [0, 0]
l2 = [1, 1, 1]
l3 = [2, 2, 2]
Output:
merged = [0, 1, 2, 0, 1, 2, 1, 2]
How can I merge these 3 lists in this specific way?
Input:
l1 = [0, 0]
l2 = [1, 1, 1]
l3 = [2, 2, 2]
Output:
merged = [0, 1, 2, 0, 1, 2, 1, 2]
If your lists don’t contain None
s, itertools.zip_longest
will produce these tuples:
>>> for t in itertools.zip_longest(l1, l2, l3):
... print(t)
(0, 1, 2)
(0, 1, 2)
(None, 1, 2)
which you can then chain together and filter the None
s out of:
merged = [x for x in itertools.chain.from_iterable(itertools.zip_longest(l1, l2, l3))
if x is not None]
Or shorter, since there’s already a list comprehension:
merged = [x for t in itertools.zip_longest(l1, l2, l3) for x in t
if x is not None]
Try this:
from functools import partial
from operator import is_not
import itertools
list(filter(partial(is_not, None), itertools.chain.from_iterable(itertools.zip_longest(l1,l2,l3))))
# [0, 1, 2, 0, 1, 2, 1, 2]