迭代时从列表中删除 [英] Removing from a list while iterating over it

查看:123
本文介绍了迭代时从列表中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

a = list(range(10))
remove = False
for b in a:
    if remove:
        a.remove(b)
    remove = not remove
print(a)

输出 [0,2,3,5,6,8,9] ,而不是 [0,2,4,6,8] 使用Python 3.2时。

Outputs [0, 2, 3, 5, 6, 8, 9], instead of [0, 2, 4, 6, 8] when using Python 3.2.


  1. 为什么输出这些特定值?

  2. 为什么没有给出错误来指示底层迭代器正在被修改?

  3. 让机制从关于这种行为的早期版本的Python?

请注意,我不是要解决这个问题,而是要了解它。

Note that I am not looking to work around the behaviour, but to understand it.

推荐答案

我辩论了一段时间后回答这个问题,因为这里曾多次提出类似的问题。但它的独特性足以让人怀疑。 (尽管如此,如果其他人投票结束,我也不会反对。)以下是对正在发生的事情的直观解释。

I debated answering this for a while, because similar questions have been asked many times here. But it's just unique enough to be given the benefit of the doubt. (Still, I won't object if others vote to close.) Here's a visual explanation of what is happening.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]       <-  b = 0; remove? no
 ^
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]       <-  b = 1; remove? yes
    ^
[0, 2, 3, 4, 5, 6, 7, 8, 9]          <-  b = 3; remove? no
       ^
[0, 2, 3, 4, 5, 6, 7, 8, 9]          <-  b = 4; remove? yes
          ^
[0, 2, 3, 5, 6, 7, 8, 9]             <-  b = 6; remove? no
             ^
[0, 2, 3, 5, 6, 7, 8, 9]             <-  b = 7; remove? yes
                ^
[0, 2, 3, 5, 6, 8, 9]                <-  b = 9; remove? no
                   ^

由于没有其他人,我会尝试回答您的其他问题:

Since no one else has, I'll attempt to answer your other questions:


为什么没有给出错误来指示底层迭代器被修改?

Why is no error given to indicate that underlying iterator is being modified?

要抛出错误而不禁止许多完全有效的循环结构,Python必须知道 lot 有关正在发生的事情,并且它可能必须获取该信息在运行时。所有这些信息都需要时间来处理。它会让速度慢很多,只是速度真正重要的地方 - 循环。

To throw an error without prohibiting many perfectly valid loop constructions, Python would have to know a lot about what's going on, and it would probably have to get that information at runtime. All that information would take time to process. It would make Python a lot slower, in just the place where speed really counts -- a loop.


有关此行为的机制是否已从早期版本的Python更改?

Have the mechanics changed from earlier versions of Python with respect to this behaviour?

简而言之,没有。或者至少我高度怀疑它,当然,自从我学习Python(2.4)以来,它一直表现得这样。坦率地说,我希望任何直接实现的可变序列都能以这种方式运行。谁知道更好,请纠正我。 (实际上,快速文档查找确认了的文本引用的Mikola 1.4版以来一直在教程中a>!)

In short, no. Or at least I highly doubt it, and certainly it has behaved this way since I learned Python (2.4). Frankly I would expect any straightforward implementation of a mutable sequence to behave in just this way. Anyone who knows better, please correct me. (Actually, a quick doc lookup confirms that the text that Mikola cited has been in the tutorial since version 1.4!)

这篇关于迭代时从列表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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