列出“怪癖”在Python中
我在交互式解释器中尝试使用列表进行一些操作,我注意到这一点:
>>> list = range(1, 11)
>>> for i in list:
... list.remove(i)
...
>>> list
[2, 4, 6, 8, 10]
任何人都可以解释为什么它留下偶数吗?现在这让我很困惑......非常感谢。
I was trying out some things with lists in the interactive interpreter and I noticed this:
>>> list = range(1, 11)
>>> for i in list:
... list.remove(i)
...
>>> list
[2, 4, 6, 8, 10]
Can anyone explain why it left even numbers? This is confusing me right now... Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
修改正在迭代的列表是不安全的。
It isn't safe to modify a list that you are iterating over.
我的猜测是 for 循环的实现如下:
每次删除一个元素时,“下一个”元素就会滑入其位置,但
i
无论如何都会递增,跳过 2 个元素。但是,ObscureRobot 是对的,这样做并不安全(这可能是未定义的行为)。
My guess is that the for loop is implemented like the following:
Every time an element is removed, the "next" element slides into its spot, but
i
gets incremented anyway, skipping 2 elements.But yes, ObscureRobot is right, it's not really safe to do this (and this is probably undefined behavior).
如果要在迭代列表时修改列表,请从后到前进行操作:
If you want to modify a list whilst iterating over it, work from back to front:
我发现使用 Python 解释这一点最简单:
请注意,(a) 在迭代列表时修改列表并 (b) 调用列表“列表”是一个坏主意。
I find this easiest to explain using Python:
Note that it's a bad idea to (a) modify a
list
while iterating over it and (b) call alist
"list".