从循环中的列表中删除项目

时间:2011-08-29 06:52:15

标签: python list

在相当长的一段时间里,我一直试图想出一种循环列表的方法并删除我所在的当前项目。我似乎无法像我希望的那样工作。它只循环一次,但我希望它循环2次。当我删除删除行时 - 它会循环2次。

a = [0, 1]
for i in a:
    z = a
    print z.remove(i)

输出:

[1]

我期待的输出:

[1] 
[0]

4 个答案:

答案 0 :(得分:8)

您在迭代时更改了列表 - z = a没有制作副本,只是在z点的a点指向for i in a[:]: # slicing a list makes a copy print i # remove doesn't return the item so print it here a.remove(i) # remove the item from the original list

尝试

while a:                # while the list is not empty
    print a.pop(0)      # remove the first item from the list

a = [i for i in a if i] # remove all items that evaluate to false
a = [i for i in a if condition(i)] # remove items where the condition is False

如果您不需要显式循环,则可以使用列表推导删除与条件匹配的项目:

{{1}}

答案 1 :(得分:3)

在循环浏览列表时,修改列表是不好的做法。创建列表的副本。 e.g:

oldlist = ['a', 'b', 'spam', 'c']
newlist = filter(lambda x: x != 'spam', oldlist)

†为了解释为什么这可能是不好的做法,请考虑序列在迭代期间更改时序列上迭代器的实现细节。如果您已删除当前项,迭代器是否应指向原始列表中的下一项或修改后的列表中的下一项?如果您的决策程序将之前的(或 next )项目移除到当前项目会怎样?


有些人不喜欢过滤器,等同于列表理解的东西:

newlist = [x for x in oldlist if x != 'spam']

答案 2 :(得分:2)

问题是您正在使用a修改remove,因此循环退出,因为索引现在超过了它的结尾。

答案 3 :(得分:1)

循环列表时,请勿尝试删除列表中的多个项目。我认为这是一般规则,你不仅要遵循python,还要遵循其他编程语言。

您可以将要删除的项目添加到单独的列表中。然后从原始列表中删除该新列表中的所有对象。