Python: Intertwining two lists

跟風遠走 提交于 2020-07-02 11:45:26

问题


What is the pythonic way of doing the following:

I have two lists a and b of the same length n, and I want to form the list

c = [a[0], b[0], a[1], b[1], ..., a[n-1], b[n-1]]

回答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?




回答2:


c = list(itertools.chain.from_iterable(itertools.izip(a, b)))



回答3:


c = [item for t in zip(a,b) for item in t]



回答4:


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




回答5:


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].)




回答6:


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


来源:https://stackoverflow.com/questions/6356041/python-intertwining-two-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!