Python以交替方式合并两个不同长度的列表

1 投票
5 回答
5916 浏览
提问于 2025-04-18 16:35

我有两个列表,我想把它们交替合并,直到其中一个列表的元素用完,然后我想继续从较长的列表中添加元素。

也就是说。

list1 = [a,b,c]

list2 = [v,w,x,y,z]

result = [a,v,b,w,c,x,y,z]

这和这个问题类似(用Python交替合并两个列表的好方法?),不过在这个问题中,合并会在第一个列表用完后停止 :(。

相关问题:

5 个回答

0

我们可以使用zip_longest,参考一下tcathcart的回答。

import itertools
result = [i for sub in itertools.zip_longest(list1, list2) for i in sub]
0

我的解决方案:

result = [i for sub in zip(list1, list2) for i in sub]

编辑:问题说明较长的列表应该在较短的列表末尾继续,而这个答案并没有做到这一点。

1

你可以使用普通的 map 函数和列表推导式:

>>> [x for t in map(None, a, b) for x in t if x]
['a', 'v', 'b', 'w', 'c', 'x', 'y', 'z']
5

你可能会对这个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']
5

这里有一个来自优秀的 toolz 的简单版本:

>>> interleave([[1,2,3,4,5,6,7,],[0,0,0]])
[1, 0, 2, 0, 3, 0, 4, 5, 6, 7]

撰写回答