开发者

Python: Intertwining two lists [duplicate]

This question already has answers here: Pythonic way to combine (interleave, interlace, intertwine) two lists in an alternating fashion? (26 answers) Closed 6 months ago.

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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜