Python: Intertwining two lists [duplicate]
What is the pythonic way of doing the following:
I have two lists a
and b
of the sa开发者_StackOverflow社区me length n
, and I want to form the list
c = [a[0], b[0], a[1], b[1], ..., a[n-1], b[n-1]]
c = [item for pair in zip(a, b) for item in pair]
Read documentation about zip.
For comparison with Ignacio's answer see this question: How do I convert a tuple of tuples to a one-dimensional list using list comprehension?
c = list(itertools.chain.from_iterable(itertools.izip(a, b)))
c = [item for t in zip(a,b) for item in t]
c = [item for i in zip(a,b) for item in i]
Alternatively you could try:
c=[(a,b)[i%2][i/2] for i in xrange(2*n)]
which is of course less readable
Here is another way:
sum(([x,y] for (x,y) in zip(a,b)), [])
(Maybe not very efficient since you form both temporary tuples (x,y) and temporary lists [x,y].)
How about this one (tested on Python 2 and 3):
list(sum(zip(a, b), ()))
or in numpy:
import numpy as np
np.vstack((a, b)).T.flatten().tolist()
精彩评论