Giacomo F
Giacomo F

Reputation: 132

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?

Upvotes: 1

Views: 94

Answers (2)

Giacomo F
Giacomo F

Reputation: 132

I actually managed to solve it trivially by dividing list d into 2 lists, one with its even elements, and the other with its odd ones.

d_even = d[0::2]
d_odds = d[1::2]

And then add both to the zip:

new_list = list(filter(None, chain.from_iterable(zip_longest(a, b, c, d_even, d_odd))))

Upvotes: 1

blhsing
blhsing

Reputation: 107040

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

Upvotes: 1

Related Questions