I want interleave 4 lists of same length in python.
I search this site and only see how to interleave 2 in python: Interleaving two lists in Python
Can give advice for 4 lists?
I have lists like this
l1 = ["a","b","c","d"] l2 = [1,2,3,4] l3 = ["w","x","y","z"] l4 = [5,6,7,8]
I want list like
l5 = ["a",1,"w",5,"b",2,"x",6,"c",3,"y",7,"d",4,"z",8]
Provided the lists are the same length, zip()
can be used to interleave four lists just like it was used for interleaving two in the question you linked:
>>> l1 = ["a", "b", "c", "d"] >>> l2 = [1, 2, 3, 4] >>> l3 = ["w", "x", "y", "z"] >>> l4 = [5, 6, 7, 8] >>> l5 = [x for y in zip(l1, l2, l3, l4) for x in y] >>> l5 ['a', 1, 'w', 5, 'b', 2, 'x', 6, 'c', 3, 'y', 7, 'd', 4, 'z', 8]
itertools.chain
and zip
:
from itertools import chain
l1 = ["a", "b", "c", "d"] l2 = [1, 2, 3, 4] l3 = ["w", "x", "y", "z"] l4 = [5, 6, 7, 8]
print(list(chain(*zip(l1, l2, l3, l4))))
Or as @PatrickHaugh suggested use chain.from_iterable
:
list(chain.from_iterable(zip(l1, l2, l3, l4)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With