现在,我已经尝试找出一种方法来遍历列表并删除当前项目。我似乎无法得到这个工作,因为我希望它。它只循环1次,但我希望它循环2次。当我删除去除线 - 它循环2次。从循环中的列表中删除项目
a = [0, 1]
for i in a:
z = a
print z.remove(i)
输出:
[1]
的输出,我期待:
[1]
[0]
现在,我已经尝试找出一种方法来遍历列表并删除当前项目。我似乎无法得到这个工作,因为我希望它。它只循环1次,但我希望它循环2次。当我删除去除线 - 它循环2次。从循环中的列表中删除项目
a = [0, 1]
for i in a:
z = a
print z.remove(i)
输出:
[1]
的输出,我期待:
[1]
[0]
这是不好的做法,修改列表,而你通过它†循环。创建列表的副本。例如: -
oldlist = ['a', 'b', 'spam', 'c']
newlist = filter(lambda x: x != 'spam', oldlist)
†对于为什么这可能是不好的做法,可以考虑实施细则孰与迭代在序列的推移,当序列迭代过程中变化的依据。如果你已经删除了当前项目,迭代器应该指向原始列表中的下一个项目还是指向修改列表中的下一个项目?如果您的决定程序取而代之将之前的(或下一个)项目移除到当前?
有些人不喜欢过滤器,与列表理解等价的东西:
newlist = [x for x in oldlist if x != 'spam']
对此方法使用列表理解而不是过滤器。 – agf
你正在改变列表,而迭代它 - 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
在循环列表时不要尝试删除多个列表项。我认为这是一个通用的规则,你不仅应该遵循python,还应该遵循其他编程语言。
您可以将要删除的项目添加到单独的列表中。然后从原始列表中删除新列表中的所有对象。
我不知道你为什么得到任何输出。我想'z.remove(i)'会返回'None'。 – wim