Python for循环或列表奇怪的行为 [英] Python strange behavior in for loop or lists
问题描述
我目前正在用python开发一个程序,而我刚刚注意到foreach循环在语言中出了什么问题,或者是列表结构。我只是简单地给出一个我的问题的泛型例子,因为我的程序和我的泛型例子都得到了同样的错误行为:
pre $ x = [1,2,2,2,2]
for i in x:
x.remove(i)
print x
好的,这里的问题很简单,我虽然认为这段代码应该从名单。那么,问题是执行后,我总是得到2个剩余的元素在列表中。
我做错了什么?感谢所有的帮助提前。
编辑:我不想清空一个列表,这只是一个例子... $ / $ b $在Python中,这是一个记录良好的行为,你不应该修改被迭代的列表。试试这个:
for i in x [:]:
x.remove(i)
I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example: Well, the problem here is simple, I though that this code was supposed to remove all elements from a list. Well, the problem is that after it's execution, I always get 2 remaining elements in the list. What am I doing wrong? Thanks for all the help in advance. Edit: I don't want to empty a list, this is just an example... This is a well-documented behaviour in Python, that you aren't supposed to modify the list being iterated through. Try this instead: The 这篇关于Python for循环或列表奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! [:]
返回一个 x
的副本。 bx = [1,2,2,2,2]
for i in x:
x.remove(i)
print x
for i in x[:]:
x.remove(i)
[:]
returns a "slice" of x
, which happens to contain all its elements, and is thus effectively a copy of x
.