我完全被这个问题困住了:
我有以下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.嗯?据我所知,迭代列表不涉及删除所有其他元素。
我错过了一些直截了当的话吗?到底是怎么回事?
答案 0 :(得分:6)
...它会跳过其他所有元素。
那是因为你继续删除它们,将列表缩短1.然后你继续下一个索引。要么倒退,要么迭代列表的副本。