[英]Insert values of one list into another at every n position
SO上有很多示例,它們將相同的單個值插入n位置的另一個列表中,但是找不到任何表明以下內容的示例:
采取以下清單:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
list2 = ['this', 'that', 'the', 'other']
每2個位置將list2的每個值插入list1以返回:
['a', 'b', 'this', 'c', 'd', 'that', 'e', 'f', 'the', 'g', 'h', 'other']
或者,只需創建一個具有相同結果的第三個列表。
您可以通過以下配方將zip
與列表理解和塊list1
使用:
from itertools import chain
def chunks(L, n):
"""Yield successive n-sized chunks from L."""
for i in range(0, len(L), n):
yield L[i:i + n]
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
list2 = ['this', 'that', 'the', 'other']
zipper = zip(chunks(list1, 2), list2)
res = list(chain.from_iterable((x, y, z) for (x, y), z in zipper))
['a', 'b', 'this', 'c', 'd', 'that', 'e', 'f', 'the', 'g', 'h', 'other']
您可以嘗試以下簡單而干凈的解決方案:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
list2 = ['this', 'that', 'the', 'other']
i=2
j=0
while(j<len(list1) and j<len(list2)):
list1.insert(i, list2[j])
i=i+3
j=j+1
print(list1)
您可以嘗試以下代碼:
def insert_list(old_list, new_list, n):
for i, val in enumerate(new_list):
old_list.insert(n+i*3, val)
return old_list
測試:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
list2 = ['this', 'that', 'the', 'other']
print(insert_list(list1, list2, 2))
輸出:
['a', 'b', 'this', 'c', 'd', 'that', 'e', 'f', 'the', 'g', 'h', 'other']
insert可用於將單個值插入列表
讓我們看看文檔中關於insert
:
list.insert(i,x)
在給定位置插入項目。 第一個參數是要插入之前該元素的索引,所以
a.insert(0, x)
插入在列表的前部,和a.insert(len(a), x)
等價於a.append(x)
。
在給定索引之前插入。 讓我們看一個牢記這一點的示例實現:
def ins_n(lst1, lst2, n): # insert every n elements
indx1 = n
indx2 = 0
while(indx1 <= len(lst1)):
lst1.insert(indx1, lst2[indx2])
indx1 += 1 + n # add `1` because we insert before the given index
indx2 += 1
return lst1
用示例列表和2
測試它:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
list2 = ['this', 'that', 'the', 'other']
print(ins_n(list1, list2, 2))
輸出:
['a', 'b', 'this', 'c', 'd', 'that', 'e', 'f', 'the', 'g', 'h', 'other']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.