This question already has an answer here:
- Interleaving Lists in Python [duplicate] 4 answers
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.
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)))
来源:https://stackoverflow.com/questions/28395945/how-to-concatenate-two-lists-so-that-elements-are-in-alternative-position