例如:
a=[1,2,3,4,5,6]
b=[7,8,9,10,11,12]
然后结果:
c=[1,7,2,8,3,9,4,10,5,11,6,12]
如何连接两个列表,以便元素处于替代位置?
我试图将它们链接到一个新列表并重新排列,但它不会到来。 如果你可以告诉我很长的路(不使用太多的内置功能)会很好。我是python的新手,在我的学校里教的不多。 谢谢。
答案 0 :(得分:3)
只需将它们与for循环相加,假设它们的长度相同:
c = []
for i in range(len(a)):
c.append(a[i])
c.append(b[i])
答案 1 :(得分:2)
对于python 3中不均匀的大小列表,您可以使用filter
和zip_longest
过滤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]
使用python2使用列表comp并使用ele is not None
过滤无:
print([ ele for ele in chain.from_iterable(zip_longest(a, b)) if ele is not None])
如果您的列表中包含None
值,请使用自定义标记值,将其用作fillvalue
中的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])
答案 2 :(得分:1)
>>> 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]
答案 3 :(得分:1)
>>> 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)))