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

查看:86
本文介绍了为什么在迭代列表时修改列表时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天全站免登陆