python for循环和remove方法 [英] python for loop and remove method

查看:108
本文介绍了python for循环和remove方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个列表,我想一一说清楚.看看这段代码:

assume we have a list , and I want to make it clear one by one. look at this code :

#code1
>>> x=[9,0,8,1,7,2,5]
>>> for i in x :
      x.remove(i)
>>> x
[0, 1, 2]

最后 x 不清楚.为什么 ?和

at last x are not clear . why ? and

#code2:
>>> for i in x :
      x.remove(x[0])
>>> x
[7, 2, 5]

这段代码就像code1.通过code3比较这两个代码,为什么它们不是这样的:

this code is like code1. compare the two codes by code3, why they are not act like this one:

#code3:
>>> while x:
    x.remove(x[0])
>>> x
[]


我还有一个关于 for/while 循环的问题,当 python 运行时:


I have another question about for/while loop , when python run :

for i in x 

while x

所有 x 内容都在内存/RAM 中吗?如果是,当 x 太大时我该怎么做才能获得更好的性能?

does all of x content are in memory/RAM ? if yes, what I can do when x are too big , for better performance?

请解释一下代码输出的差异:

plz explain about difference of outputs in codes:

推荐答案

当你说 for i in x 时,你正在使用一个 迭代器.

When you say for i in x, you are using an iterator.

这个迭代器在循环运行时将当前位置存储在 x 中.如果在循环仍在进行时修改正在迭代的对象的状态 (x),则迭代器对象不知道这一点.

This iterator stores the current position in x as the loop runs. If you modify the status of the object over which you are iterating (x) while the loop is still going, the iterator object does not know this.

这就是为什么在 x 中使用 for i 没有运行正确的次数:删除元素时列表的大小会缩小,导致迭代器超出 (现在缩小)列表,即使列表尚未为空,也会导致循环终止.while 循环没有使用迭代器:它只是一个条件检查.

That's why using the for i in x doesn't run the correct number of times: the size of the list shrinks when you remove elements, leading to the iterator being beyond the end of the (now shrunken) list, causing the loop to terminate even though the list is not yet empty. The while loop isn't using an iterator: it's just a conditional check.

您可以通过遍历 x副本来查看此操作:

You can see this in action by iterating over a copy of x:

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

或者通过迭代x中的索引:

Or by iterating over the indices in x:

for i in range(len(x)):
    x.remove(x[0])

要回答您的第二个问题,如果 x 很大,请使用 生成器函数 而不是真正的列表.迭代生成器的结果仍然看起来像 for i in x,但是列表不需要完全物化以便您迭代它.

To answer your second question, if x is big, use a generator function instead of a real list. Iterating over the results of the generator still looks like for i in x, but the list does not need to be entirely materialized for you to iterate over it.

这篇关于python for循环和remove方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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