以交替方式组合两个列表的 Pythonic 方式? [英] Pythonic way to combine two lists in an alternating fashion?
本文介绍了以交替方式组合两个列表的 Pythonic 方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表,其中第一个保证比第二个多一个项目.我想知道创建一个新列表的最 Pythonic 方法,该列表的偶数索引值来自第一个列表,其奇数索引值来自第二个列表.
# 示例输入list1 = ['f', 'o', 'o']list2 = ['你好','世界']# 想要的输出['f', '你好', 'o', '世界', 'o']
这有效,但不漂亮:
list3 = []为真:尝试:list3.append(list1.pop(0))list3.append(list2.pop(0))除了索引错误:休息
还有什么办法可以实现?最 Pythonic 的方法是什么?
解决方案
这是一种通过切片来实现的方法:
<预><代码>>>>list1 = ['f', 'o', 'o']>>>list2 = ['你好','世界']>>>结果 = [无]*(len(list1)+len(list2))>>>结果[::2] = 列表1>>>结果[1::2] = 列表2>>>结果['f', '你好', 'o', '世界', 'o']I have two lists, the first of which is guaranteed to contain exactly one more item than the second. I would like to know the most Pythonic way to create a new list whose even-index values come from the first list and whose odd-index values come from the second list.
# example inputs
list1 = ['f', 'o', 'o']
list2 = ['hello', 'world']
# desired output
['f', 'hello', 'o', 'world', 'o']
This works, but isn't pretty:
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?
解决方案
Here's one way to do it by slicing:
>>> 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 方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文