Python中循环迭代的重做

2024-06-17 13:30:33 发布

您现在位置:Python中文网/ 问答频道 /正文

Python是否有一些语言中存在的“redo”语句?

(“redo”语句是一个语句,它(就像“break”或“continue”)会影响循环行为-它在最内部循环的开始处跳转并再次开始执行。)


Tags: 语言语句breakcontinueredo
3条回答

不,Python不直接支持redo。有一个选项可能会让嵌套循环变得非常糟糕,比如:

for x in mylist:
    while True:
        ...
        if shouldredo:
            continue  # continue becomes equivalent to redo
        ...
        if shouldcontinue:
            break     # break now equivalent to continue on outer "real" loop
        ...
        break  # Terminate inner loop any time we don't redo

但这意味着,在“redoable”块中,不诉诸异常、标记变量或将整个东西打包为函数,就不可能break使用外部循环。

或者,使用一个直接的while循环来复制for循环为您做的事情,显式地创建和推进迭代器。它有自己的问题(continue实际上是redo默认情况下,您必须显式地为“real”continue推进迭代器),但它们并不可怕(只要您使用continue注释,以表明您打算redocontinue,以避免混淆维护者)。要允许redo和其他循环操作,您需要执行以下操作:

# Create guaranteed unique sentinel (can't use None since iterator might produce None)
sentinel = object()
iterobj = iter(mylist)  # Explicitly get iterator from iterable (for does this implicitly)
x = next(iterobj, sentinel)  # Get next object or sentinel
while x is not sentinel:     # Keep going until we exhaust iterator
    ...
    if shouldredo:
        continue
    ...
    if shouldcontinue:
        x = next(iterobj, sentinel)  # Explicitly advance loop for continue case
        continue
    ...
    if shouldbreak:
        break
    ...
    # Advance loop
    x = next(iterobj, sentinel)

上面的操作也可以用try/except StopIteration:来完成,而不是用一个sentinel来包装两个参数next,但是用它来包装整个循环可能会有其他StopIteration源被捕获的风险,并且在一个有限的范围内对内部和外部的next调用都正确地执行这一操作会非常难看(比基于sentinel的方法更糟糕)。

不,没有。我建议使用while循环并将check变量重置为初始值。

count = 0
reset = 0
while count < 9:
   print 'The count is:', count
   if not someResetCondition:
       count = count + 1

我在学习perl时遇到了同样的问题,我找到了这个页面。

遵循perl手册:

my @words = qw(fred barney pebbles dino wilma betty);
my $error = 0;

my @words = qw(fred barney pebbles dino wilma betty);
my $error = 0;

foreach (@words){
    print "Type the word '$_':";
    chomp(my $try = <STDIN>);
    if ($try ne $_){
        print "Sorry - That's not right.\n\n";
        $error++;
        redo;
    }
}

以及如何在Python上实现它?? 遵循准则:

tape_list=['a','b','c','d','e']

def check_tape(origin_tape):
    errors=0
    while True:
        tape=raw_input("input %s:"%origin_tape)
        if tape == origin_tape:
            return errors
        else:
            print "your tape %s,you should tape %s"%(tape,origin_tape)
            errors += 1
            pass

all_error=0
for char in tape_list:
    all_error += check_tape(char)
print "you input wrong time is:%s"%all_error

Python没有“redo”语法,但是我们可以在一些函数中进行一个“while”循环,直到我们输入列表时得到所需的内容。

相关问题 更多 >