每隔n个位置将列表中的项目插入到另一个列表中 [英] Insert items from list to another list every n positions
问题描述
我有以下列表.
vector = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
inserted_elements = [2, 2, 2, 2, 2]
我想通过每两个元素插入以下内容.
I want to get the following by inserting every two elements.
output = [1, 2, 2, 3, 4, 2, 5, 6, 2, 7, 8, 2, 9, 10, 2]
不仅Python列表而且使用numpy数组的答案都很好.
Not only the Python list but also the answer using numpy array is fine.
推荐答案
这是一个 <基于 code>itertools 的方法,该方法也适用于从一个列表插入到另一个列表的任意数量的元素.为此,我定义了一个生成器函数,它将每个 i
项中的 l2
中的元素和元素插入 l1
中:
Here's an itertools
based approach, which also works for an arbitrary number of elements to be inserted from one list to the other. For this I've defined a generator function, which will insert and element from l2
into l1
every i
items:
def insert_every_n(l1, l2, k):
i1, i2 = iter(l1), iter(l2)
while True:
try:
yield from islice(i1, k)
yield next(i2)
except StopIteration:
return
这可以通过使用 从
产生的收益所产生的项与切片的可迭代项中的项一样多,因此可迭代项用尽了(用于g中v的快捷方式:yield v
).
最后,我们可以用 try
/ expect
包裹 yield
语句,以捕获 StopIteration
警告.
Finally we can wrap the yield
statements with a try
/expect
to catch the StopIteration
warning.
让我们尝试以下示例:
vector = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
inserted_elements = [2, 2, 2, 2, 2]
list(insert_every_n(vector, inserted_elements, k=2))
# [1, 2, 2, 3, 4, 2, 5, 6, 2, 7, 8, 2, 9, 10, 2]
如果我们想每3个项目添加一个 l2
个项目:
And if we wanted to add an item of l2
every 3 items:
vector = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
inserted_elements = [2, 2, 2, 2]
list(insert_every_n(vector, inserted_elements, k=3))
# [1, 2, 3, 2, 4, 5, 6, 2, 7, 8, 9, 2, 10, 2]
这篇关于每隔n个位置将列表中的项目插入到另一个列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!