Note: There is a subtlety when the sequence is being modified by the
loop (this can only occur for mutable sequences, e.g. lists). An
internal counter is used to keep track of which item is used next, and
this is incremented on each iteration. When this counter has reached
the length of the sequence the loop terminates. This means that if the
suite deletes the current (or a previous) item from the sequence, the
next item will be skipped (since it gets the index of the current item
which has already been treated). Likewise, if the suite inserts an
item in the sequence before the current item, the current item will be
treated again the next time through the loop. This can lead to nasty
bugs that can be avoided by making a temporary copy using a slice of
the whole sequence, e.g.,
因为你在循环的时候改变了列表,这几乎总是个坏主意。下面演示一下发生了什么:
这是文件中的相关部分,它告诉我们这是个坏主意:
您可以使用非常简单的列表理解来实现这一点:
相关问题 更多 >
编程相关推荐