我有两个列表,list1
和 list2
.
这里 len(list2) << len(list1)
.
现在我想合并这两个列表,使得最终列表的每个 第 n 个元素 来自 list2
和来自list1
的其他人.
例如:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
list2 = ['x', 'y']
n = 3
现在最终的列表应该是:
['a', 'b', 'x', 'c', 'd', 'y', 'e', 'f', 'g', 'h']
什么是最Pythonic如何实现?
我想添加 list2
的所有元素到最终列表,最终列表应包括来自 list1
的所有元素和 list2
.
最佳答案
将较大的列表作为迭代器可以很容易地为较小列表的每个元素获取多个元素:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
list2 = ['x', 'y']
n = 3
iter1 = iter(list1)
res = []
for x in list2:
res.extend([next(iter1) for _ in range(n - 1)])
res.append(x)
res.extend(iter1)
>>> res
['a', 'b', 'x', 'c', 'd', 'y', 'e', 'f', 'g', 'h']
这避免了 insert
,这对于大型列表来说可能是昂贵的,因为每次都需要重新创建整个列表。
关于python - 通过放置一个列表中的第 n 个项目和另一个列表中的其他项目来合并 Python 中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34692738/