Python for循环或列表奇怪的行为 [英] Python strange behavior in for loop or lists

查看:106
本文介绍了Python for循环或列表奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用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)

[:] 返回一个 c $ c> x ,它恰好包含了它的所有元素,因此是 x 的副本。 b

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        

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:

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

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

这篇关于Python for循环或列表奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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