How to concatenate two lists so that elements are in alternative position? [duplicate]

狂风中的少年 提交于 2019-12-01 14:19:23

Just append them with a for loop, assuming they're the same length:

c = []

for i in range(len(a)):
    c.append(a[i])
    c.append(b[i])

for uneven size lists in python 3 you can use filter and zip_longest filtering None:

a = [1,2,3,4,5,6]
b = [7,8,9,10,11,12,13]

from itertools import chain, zip_longest

print(list(filter(None.__ne__ ,chain.from_iterable(zip_longest(a,b)))))
[1, 7, 2, 8, 3, 9, 4, 10, 5, 11, 6, 12, 13]

Using python2 use a list comp and filter None's with ele is not None:

print([ ele for ele in chain.from_iterable(zip_longest(a, b)) if ele is not None])

If you may have None as a value in your lists use a custom sentinel value, using that as the fillvalue in zip_longest:

my_sent = object()
print([ ele for ele in chain.from_iterable(zip_longest(a, b,fillvalue=my_sent)) if ele is not my_sent])

Using zip and list comprehension:

>>> a = [1, 2, 3, 4, 5, 6]
>>> b = [7, 8, 9, 10, 11, 12]
>>> [x for xs in zip(a, b) for x in xs]
[1, 7, 2, 8, 3, 9, 4, 10, 5, 11, 6, 12]
>>> import itertools
>>> a = [1, 2, 3, 4, 5, 6]
>>> b = [7, 8, 9, 10, 11, 12]
>>> print list(itertools.chain.from_iterable(zip(a, b)))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!