用Pythonic方式以交替方式组合两个列表的方法?

我有两个列表,保证其中一个比第二个多包含一个项目。我想知道最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化的方法?


慕运维8079593
浏览 455回答 3
3回答

杨魅力

这是切片的一种方法:>>> 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']

狐的传说

在itertools文档中有一个配方:from itertools import cycle, islicedef 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))

呼唤远方

如果没有itertools,并假设l1比l2长1个项目:>>> sum(zip(l1, l2+[0]), ())[:-1]('f', 'hello', 'o', 'world', 'o')使用itertools并假设列表不包含None:>>> filter(None, sum(itertools.izip_longest(l1, l2), ()))('f', 'hello', 'o', 'world', 'o')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python