我有两个列表,我想以交替的方式组合它们,直到一个列表用完,然后我想继续从更长的列表中添加元素。
又名。
list1 = [a,b,c]
list2 = [v,w,x,y,z]
result = [a,v,b,w,c,x,y,z]
类似于这个问题(以交替方式组合两个列表的python方式?),除了在第一个列表用完后列表停止组合:(.
下面是来自优秀的工具z的简单版本:
>>> interleave([[1,2,3,4,5,6,7,],[0,0,0]])
[1, 0, 2, 0, 3, 0, 4, 5, 6, 7]
您可能对itertools
配方感兴趣:
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
例如:>>> from itertools import cycle, islice
>>> list1 = list("abc")
>>> list2 = list("uvwxyz")
>>> list(roundrobin(list1, list2))
['a', 'u', 'b', 'v', 'c', 'w', 'x', 'y', 'z']
您可以使用普通的map
和列表推导:
>>> [x for t in map(None, a, b) for x in t if x]
['a', 'v', 'b', 'w', 'c', 'x', 'y', 'z']
我的解决方案:
result = [i for sub in zip(list1, list2) for i in sub]
编辑:问题指定较长列表应该在较短列表的末尾继续,这个答案不这样做。
我们可以使用zip_longest来获取答案
import itertools
result = [i for sub in itertools.zip_longest(list1, list2) for i in sub]