[英]How do I get certain values at the end of my list, get these values every so often, and insert in certain positions in my original list in Python?
假設我有一個這樣的列表:
ls = [a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14]
我想通過執行以下操作來獲取此列表的最后六個條目:
new_ls = ls[-6:]
從這里開始,我想獲取這個新列表並獲取每兩個new_ls
並將其插入我的每兩個ls
之間,以便我的輸出如下所示:
output_ls = [a1,a2,a9,a10,a3,a4,a11,a12,a5,a6,a13,a14,a7,a8]
我怎樣才能做到這一點? 謝謝!
這是我迄今為止在我的代碼中嘗試過的,total_ls 有 108 個元素:
new_ls1 = list(xy4b1.items())
new_ls2 = list(xy4b2.items())
total_ls = new_ls1 + new_ls2
size = 2
start = -36
test_ls = total_ls[start:start+size]
total_ls.insert(4,test_ls)
我只能將我的“最后一個元素”插入到我的原始列表中。 我沒有完成for
循環實現,因為我不知道如何。
應要求添加變量 NewList 的 Python 示例:
ls = ['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10']
newList= ls[-4:]
ls = ls[0:len(ls)-4]
print(ls)
print(newList)
endList=[]
isPutFromNewList = True
amountToTakeFromNewList =2
amountOfOldListToHaveBetween=6
lsCounter=0;
newListCounter=0
i=0
while(len(endList)!=(len(ls)+len(newList))):
if((i%amountOfOldListToHaveBetween==0 and not isPutFromNewList) or (i%amountToTakeFromNewList==0 and isPutFromNewList)):
isPutFromNewList = not isPutFromNewList
if(isPutFromNewList and newListCounter<len(newList)):
endList.append(newList[newListCounter])
newListCounter=newListCounter+1
if(not isPutFromNewList and lsCounter<len(ls)):
endList.append(ls[lsCounter])
lsCounter=lsCounter+1
i= i+1
print("end list:",endList)
下面的 JS 示例,因為我寫得很開心:
var ls = ['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10']; var newList= ls.slice(-4) ls = ls.slice(0,ls.length-4) console.log(ls); console.log(newList); var endList=[]; var isPutFromNewList = true; var lsCounter=0; var newListCounter=0; for(var i=0 ;(endList.length!=(ls.length+newList.length));i++){ if(i%2==0){ isPutFromNewList = !isPutFromNewList; } if(isPutFromNewList && newListCounter<newList.length){ endList.push(newList[newListCounter]); newListCounter++; } if(! isPutFromNewList && lsCounter<ls.length){ endList.push(ls[lsCounter]); lsCounter++; } } console.log("end list:",endList);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.