我有两个名单,其中第一个保证比第二个包含正好多一个项。我想知道创建一个新列表的最 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
How else can this be achieved? What's the most Pythonic approach?
如果您需要处理 不匹配的长度的列表(例如,第二个列表更长,或者第一个列表比第二个列表具有多于一个元素) ,这里的一些解决方案可以起作用,而其他解决方案则需要进行调整。有关更具体的答案,请参见 如何交错两个不同长度的列表?将多余的元素保留在末尾,或者参见 如何在 python 中优雅地交错两个长度不均匀的列表?尝试均匀地散布元素。