如何在列表末尾获取某些值,每隔一段时间获取这些值,并在Python原始列表的某些位置插入这些值?

2024-06-09 13:50:20 发布

您现在位置: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]

我该怎么做?谢谢

这是我迄今为止在代码中尝试过的,总共有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循环实现,因为我不知道如何实现


Tags: a2列表newa1startlsa10a3
1条回答
网友
1楼 · 发布于 2024-06-09 13:50:20

应请求添加变量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示例,因为我写它很有趣:

&13; 第13部分,;
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);
和#13;
和#13;

相关问题 更多 >