为什么在迭代列表时修改列表,Python 会跳过元素? [英] Why does Python skip elements when I modify a list while iterating over it?

查看:29
本文介绍了为什么在迭代列表时修改列表,Python 会跳过元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用 python 开发一个程序,我刚刚注意到语言中的 foreach 循环或列表结构有问题.我将仅举一个通用示例来简化我的问题,因为我的程序和通用示例都出现了相同的错误行为:

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:

x = [1,2,2,2,2]

for i in x:
    x.remove(i)

print x        

嗯,这里的问题很简单,我认为这段代码应该从列表中删除所有元素.好吧,问题是它执行后,我总是在列表中得到 2 个剩余元素.

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.

我不想清空列表,这只是一个例子...

I don't want to empty a list, this is just an example...

推荐答案

这是 Python 中记录良好的行为,您不应修改正在迭代的列表.试试这个:

This is a well-documented behaviour in Python, that you aren't supposed to modify the list being iterated through. Try this instead:

for i in x[:]:
    x.remove(i)

[:] 返回 x 的切片",它恰好包含它的所有元素,因此实际上是 x 的副本代码>.

The [:] returns a "slice" of x, which happens to contain all its elements, and is thus effectively a copy of x.

这篇关于为什么在迭代列表时修改列表,Python 会跳过元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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