如何在循环列表本身而不删除列表时删除列表元素 [英] How to delete list elements while cycling the list itself without duplicate it

查看:109
本文介绍了如何在循环列表本身而不删除列表时删除列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此Python中,我花了一点时间进行声明:

I lost a little bit of time in this Python for statement:

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()

它没有按我预期的那样工作,因为当清除"中的循环删除列表中的第一个对象时,第二个对象移到列表的开头,循环结束.

It doesn't work as I expected because when the cycle in "purge" delete the first object in list the second one is shifted to the beginning of the list and the cycle is ended.

我解决了在for循环之前复制self.list的问题:

I solved duplicating self.list before the for cycle:

...
local_list = self.list[:]
for object in local_list:
...

我想for语句停止工作,因为我正在更改原始列表的长度.有人可以澄清这一点吗?

I suppose that the for statement stop working because I'm changing the length of the original list. Can someone clarify this point ?

还有没有更优雅"的方法来解决此问题?如果列表中元素过多,那么每次都复制它似乎不是一个好主意.

And is there a more "elegant" way to solve this problem ? If I have more than few elements inside the list, duplicating it every time does not seem a good idea.

也许filter()函数是正确的,但我希望有其他方法(如有).

Maybe the filter() function is the right one but i whish to have some other approach if any.

我是新手.

总结您的有用答案:

  • 永远不要编辑您要循环播放的列表
  • 复制列表或使用列表理解
  • 复制列表不会浪费您的内存,在这种情况下,谁会介意

推荐答案

过滤器(或列表理解)是解决之道.如果您想就地执行此操作,则可以执行以下操作:

Filter (or list comprehension) IS the way to go. If you want to do it inplace, something like this would work:

purge = []
for i,object in enumerate(self.list):
    if object.mycond()
        purge.append(i)
for i in reversed(purge):
    del self.list[i]

或者,可以通过理解来创建清除列表,快捷方式如下:

Or alternatively, the purge list can be made with a comprehension, a shortcut version looks like:

for i in reversed([ i for (i,o) in enumerate(self.list) if o.mycond() ]):
    del self.list[i]

这篇关于如何在循环列表本身而不删除列表时删除列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆