在for循环中移回迭代

hem*_*ker 22 python for-loop

所以我想做这样的事情:

for i in range(5):
    print(i);
    if(condition==true):
        i=i-1;
Run Code Online (Sandbox Code Playgroud)

然而,无论出于何种原因,即使我正在减少我,循环似乎也没有注意到.有没有办法重复迭代?

Gab*_*abe 26

forPython中的循环总是向前发展.如果您希望能够向后移动,则必须使用其他机制,例如while:

i = 0
while i < 5:
    print(i)
    if condition:
        i=i-1
    i += 1
Run Code Online (Sandbox Code Playgroud)

甚至更好:

i = 0
while i < 5:
    print(i)
    if condition:
        do_something()
        # don't increment here, so we stay on the same value for i
    else:
        # only increment in the case where we're not "moving backwards"
        i += 1
Run Code Online (Sandbox Code Playgroud)


Tho*_*anz 6

Python循环使用range是按照设计与C/C++/Java for-loops不同.对于每次迭代,range(5)无论你i在中间做什么,i都设置为下一个值.

您可以使用while循环:

i = 0
while i<5:
    print i
    if condition:
        continue
    i+=1
Run Code Online (Sandbox Code Playgroud)

但说实话:我会退后一步,再想一想你原来的问题.可能你会找到一个更好的解决方案,因为这样的循环总是容易出错.这就是为什么Python for-loops被设计为不同的原因.


wim*_*wim 5

你对 Python 中的循环有误解。循环for并不关心你i在每次迭代时做什么,因为它与循环的逻辑根本无关。修改i只是重新绑定局部变量。

您需要使用 while 循环来实现您期望的行为,其中 的状态确实i会影响循环的控制流:

import random

i = 0
while i < 5:
    print(i)
    i += 1
    if random.choice([True, False]):
        i -= 1
Run Code Online (Sandbox Code Playgroud)