在for循环中移回迭代 [英] Moving back an iteration in a for loop

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

问题描述

所以我想要做这样的事情:

pre $ 为范围(5):
print(一世);
if(condition == true):
i = i-1;

然而,无论出于什么原因,即使我正在递减我,循环似乎并不注意。有没有什么办法可以重复迭代?

解决方案

for Python总是前进。如果您希望能够向后移动,您必须使用不同的机制,如 :
$ p> i = 0
while i< 5:
print(i)
如果条件:
i = i-1
i + = 1

甚至更好:

  i = 0 
while i< 5:
print(i)
如果条件:
do_something()
#在这里不增加,所以我们保持相同的值为
else:
#只在我们没有倒退的情况下增加
i + = 1


So I want to do something like this:

for i in range(5):
    print(i);
    if(condition==true):
        i=i-1;

However, for whatever reason, even though I'm decrementing i, the loop doesn't seem to notice. Is there any way to repeat an iteration?

解决方案

for loops in Python always go forward. If you want to be able to move backwards, you must use a different mechanism, such as while:

i = 0
while i < 5:
    print(i)
    if condition:
        i=i-1
    i += 1

Or even better:

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

这篇关于在for循环中移回迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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