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

 ̄綄美尐妖づ 提交于 2019-12-04 02:06:12

问题


for example:

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

then result:

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

How do you concatenate two lists,so that the elements are in alternative positions??

i have tried to link them in to a new list and rearrange but its not coming. it would be nice if you could tell me the long way(without using built in functions too much).I m new to python and not much is taught in my school. Thank you.


回答1:


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



回答2:


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



回答3:


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]



回答4:


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


来源:https://stackoverflow.com/questions/28395945/how-to-concatenate-two-lists-so-that-elements-are-in-alternative-position

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