Skip to main content
 首页 » 编程设计

python之在遍历列表范围的循环中删除对象

2025年05月04日18findumars

我有一个列表,由[开始位置、停止位置、[带有这些位置的样本名称]]组成

我的目标是删除具有精确开始和停止位置的重复项,并将额外的样本添加到样本名称部分。我遇到的问题是,当我从列表中删除时,我最终遇到了超出范围的错误,因为它没有在循环中重新计算 len(list) 。

for g in range (len(list)) : 
 
    for n in range(len(list)): 
    #compares the start and stop position of one line to the start and stop of another line  
          if (list[g][0]==list[n+1][0] and list[g][1]==[n+1][1]) 
          #adds new sample numbers to first start and stop entry with duplication 
          labels1=list[g][2] 
          labels2=list[n+1][2] 
          labels=labels1+labels2 
          list[g][2]=labels 
    #now delete the extra line 
          del list[n+1] 

请您参考如下方法:

我不确定我明白你想要什么,但可能是这样的:

from collections import defaultdict 
d = defaultdict(list) 
for start, stop, samples in L1: 
    d[start, stop].extend(samples) 
L2 = [[start, stop, samples] for (start, stop), samples in d.items()] 

这将占用 L1:

L1 = [ [1, 5, ["a", "b", "c"]], [3, 4, ["d", "e"]], [1, 5, ["f"]] ] 

并制作 L2:

L2 = [ [1, 5, ["a", "b", "c", "f"]], [3, 4, ["d", "e"]] ] 

请注意,这不能保证 L2 中的元素顺序与 L1 中的元素顺序相同,但从您的问题来看,这无关紧要。