Python 如何更改for循环的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14785495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change index of a for loop?
提问by drum
Suppose I have a for loop:
假设我有一个 for 循环:
for i in range(1,10):
if i is 5:
i = 7
I want to change iif it meets certain condition. I tried this but didn't work.
How do I go about it?
i如果满足某些条件,我想更改。我试过这个,但没有用。我该怎么做?
采纳答案by Volatility
For your particular example, this will work:
对于您的特定示例,这将起作用:
for i in range(1, 10):
if i in (5, 6):
continue
However, you would probably be better off with a whileloop:
但是,使用while循环可能会更好:
i = 1
while i < 10:
if i == 5:
i = 7
# other code
i += 1
A forloop assigns a variable (in this case i) to the next element in the list/iterable at the start of each iteration. This means that no matter what you do inside the loop, iwill become the next element. The whileloop has no such restriction.
甲for环分配一个变量(在这种情况下i/在每次迭代开始时)到下一个元素列表中的迭代。这意味着无论你在循环内部做什么,i都将成为下一个元素。该while循环有没有这样的限制。
回答by Nerf Herder
This concept is not unusual in the C world, but should be avoided if possible. Nonetheless, this is how I implemented it, in a way that I felt was clear what was happening. Then you can put your logic for skipping forward in the index anywhere inside the loop, and a reader will know to pay attention to the skip variable, whereas embedding an i=7 somewhere deep can easily be missed:
这个概念在 C 世界中并不少见,但应尽可能避免。尽管如此,这就是我实施它的方式,我觉得很清楚发生了什么。然后,您可以将向前跳过的逻辑放在循环内任何位置的索引中,读者就会知道要注意跳过变量,而在某处深处嵌入 i=7 很容易被遗漏:
skip = 0
for i in range(1,10):
if skip:
skip -= 1
continue
if i=5:
skip = 2
<other stuff>
回答by timgeb
A little more background on why the loop in the question does not work as expected.
关于为什么问题中的循环没有按预期工作的更多背景知识。
A loop
一个循环
for i in iterable:
# some code with i
is basicallya shorthand for
是基本的速记
iterator = iter(iterable)
while True:
try:
i = next(iterator)
except StopIteration:
break
# some code with i
So the forloop extracts values from an iterator constructed from the iterable one by one and automatically recognizes when that iterator is exhausted and stops.
因此,for循环从一个由可迭代对象构建的迭代器中提取值,并自动识别该迭代器何时耗尽并停止。
As you can see, in each iteration of the whileloop i is reassigned, therefore the value of iwill be overridden regardless of any other reassignments you issue in the # some code with ipart.
正如你所看到的,在每次迭代while循环我被重新分配,因此值i将被覆盖,无论您在发出任何其他的重新分配的# some code with i一部分。
For this reason, forloops in Python are not suited for permanent changes to the loop variable and you should resort to a whileloop instead, as has already been demonstrated in Volatility's answer.
出于这个原因,forPython 中的循环不适合对循环变量进行永久更改,您应该while改用循环,正如 Volatility 的答案中已经证明的那样。

