listpython-itertoolspairwise

Combine lists alternating elements one by one or two by two


I have 4 lists:

a = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8"]

b = ["b1", "b2", "b3", "b4", "b5", "b6"]

c = ["c1", "c2", "c3", "c4", "c5"]

d = ["d1", "d2", "d3", "d4", "d5", "d6", "d7"]

I need to create a list alternating the elements one by one until possible, BUT for the last list I need to take them 2 by 2 (also until possible). So the result should be:

new_list = ["a1", "b1", "c1", "d1", "d2", "a2", "b2", "c2", "d3", "d4", "a3", "b3", 
            "c3", "d5", "d6", "a4", "b4", "c4", "d7", "a5", "b5", "c5", "a6", "b6", 
            "a7", "a8"]

I know for alternating one by one you could use itertools like:

import itertools
book_list = [x for x in itertools.chain.from_iterable(itertools.zip_longest(a,b, c, d)) if x is not None]

But I do I make sure for list d I take 2 elements instead of just one? Can I introduce a pairwise() somehow on list d?


Solution

  • You can create an iterator from d and zip it twice to draw from the sequence twice per iteration:

    d2 = iter(d)
    new_list = list(filter(None, chain.from_iterable(zip_longest(a, b, c, d2, d2))))
    

    Demo: https://replit.com/@blhsing/MarriedOrderlyPoint