Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interleave 4 lists of same length python [duplicate]

Tags:

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] 
like image 672
机场之王 Avatar asked Jun 12 '18 03:06

机场之王


2 Answers

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] 
like image 155
Sash Sinha Avatar answered Oct 05 '22 22:10

Sash Sinha


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)))
like image 39
Austin Avatar answered Oct 05 '22 23:10

Austin