以一种交替的方式将两个列表组合在一起?

2024-04-25 09:06:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个列表,其中第一个列表保证比第二个列表多包含一个条目。我想知道创建一个新列表的最python方法,该列表的偶数索引值来自第一个列表,奇数索引值来自第二个列表。

# example inputs
list1 = ['f', 'o', 'o']
list2 = ['hello', 'world']

# desired output
['f', 'hello', 'o', 'world', 'o']

这很管用,但并不漂亮:

list3 = []
while True:
    try:
        list3.append(list1.pop(0))
        list3.append(list2.pop(0))
    except IndexError:
        break

不然怎么能做到呢?什么是最Python的方法?


Tags: 方法hello列表worldexample条目popinputs
3条回答

这应该符合您的要求:

>>> iters = [iter(list1), iter(list2)]
>>> print list(it.next() for it in itertools.cycle(iters))
['f', 'hello', 'o', 'world', 'o']

^{} documentation中有一个配方:

from itertools import cycle, islice

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

有一种方法可以通过切片来实现:

>>> list1 = ['f', 'o', 'o']
>>> list2 = ['hello', 'world']
>>> result = [None]*(len(list1)+len(list2))
>>> result[::2] = list1
>>> result[1::2] = list2
>>> result
['f', 'hello', 'o', 'world', 'o']

相关问题 更多 >