Skip to main content
 首页 » 编程设计

Python 在遍历列表后删除列表中的一半元素

2025年05月04日18mayingbao

我完全被这个难住了:

我有以下 python 代码:

def remove(self, widgets): 
    for widget in widgets: 
        widget_found = False 
        for widget_sig in self.widgets: 
            if widget_sig.id == widget: 
                #remove all objects from selected widget 
                widget_found = True 
                to_remove = widget_sig.objs 
                for obj in to_remove: 
                    #objs are all intances of oo_canvas classes 
                    obj.destroy() 
                    self._build(widget, obj) 
        if not widget_found: 
            #if we iterated through the entire list and still couldn't find anything 
            raise mockingbird_errs.InternalMockingbirdError("The requested widget was not registered with this builder: "+str(widget)) 

这应该很简单。问题是,它永远不会正确地遍历 to_remove。出于某种原因,它会跳过所有其他元素。更令人困惑的是,如果我让它在 for 循环前后打印 to_remove 的长度,它会打印 254 和 127。嗯?据我所知,遍历列表并不涉及删除所有其他元素。

我是不是漏掉了什么直截了当的东西?这到底是怎么回事?

请您参考如下方法:

... it skips every other element.

那是因为您一直在删除它们,将列表缩短 1。然后您转到下一个索引。要么向后工作,要么迭代列表的副本。