相关疑难解决方法(0)

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

我有两个列表,第一个列表保证只包含一个列表而不是第二个列表.我想知道创建一个新列表的最Pythonic方法,其中偶数索引值来自第一个列表,其奇数索引值来自第二个列表.

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

# desired output
['f', 'hello', 'o', 'world', 'o']
Run Code Online (Sandbox Code Playgroud)

这有效,但并不漂亮:

list3 = []
while True:
    try:
        list3.append(list1.pop(0))
        list3.append(list2.pop(0))
    except IndexError:
        break
Run Code Online (Sandbox Code Playgroud)

如何实现这一目标呢?什么是最Pythonic方法?

python

75
推荐指数
8
解决办法
5万
查看次数

标签 统计

python ×1