1

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]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Shahar
  • 29
  • 4

2 Answers2

5

If your lists don’t contain Nones, 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 Nones 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]
Ry-
  • 218,210
  • 55
  • 464
  • 476
0

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]
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24