我在这个 Python for 语句中浪费了一点时间:
class MyListContainer:
def __init__(self):
self.list = []
def purge(self):
for object in self.list:
if (object.my_cond()):
self.list.remove(object)
return self.list
container = MyListContainer()
# now suppose both obj.my_cond() return True
obj1 = MyCustomObject(par)
obj2 = MyCustomObject(other_par)
container.list = [obj1, obj2]
# returning not an empty list but [obj2]
container.purge()
它不像我预期的那样工作,因为当“清除”中的循环删除列表中的第一个对象时,第二个对象被转移到列表的开头并且循环结束。
我在 for 循环之前解决了复制 self.list 的问题:
...
local_list = self.list[:]
for object in local_list:
...
我想 for 语句停止工作是因为我正在更改原始列表的长度。有人可以澄清这一点吗?
有没有更“优雅”的方法来解决这个问题?如果列表中有多个元素,那么每次都复制它似乎不是一个好主意。
也许 filter() 函数是正确的,但如果有的话,我希望有其他方法。
我是新手。
To summarize your useful answers:
- Never edit a list you are looping
- Duplicate the list or use list comprehensions
- Duplicating a list could not waste your memory or in this case who's mind about it