gpt4 book ai didi

以交替方式组合(交错、交错、交织)两个列表的 Pythonic 方式?

转载 作者:IT老高 更新时间:2023-10-28 21:38:02 27 4
gpt4 key购买 nike

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

# 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

还有什么方法可以做到这一点?最 Pythonic 的方法是什么?


如果您需要处理长度不匹配的列表(例如,第二个列表较长,或者第一个列表比第二个多一个元素),这里的一些解决方案将有效,而其他人将需要调整。有关更具体的答案,请参阅 How to interleave two lists of different length?将多余的元素留在最后,或 How to elegantly interleave two lists of uneven length in python?尽量均匀地穿插元素。

最佳答案

这是一种通过切片来实现的方法:

>>> 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']

关于以交替方式组合(交错、交错、交织)两个列表的 Pythonic 方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3678869/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com