简体   繁体   English

python:重启循环

[英]python: restarting a loop

i have: 我有:

for i in range(2,n):
    if(something):
       do something
    else:
       do something else
       i = 2 **restart the loop

But that doesn't seem to work. 但这似乎不起作用。 Is there a way to restart that loop? 有没有办法重新启动该循环?

Thanks 谢谢

You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer. 您可能需要考虑使用该逻辑适用的不同类型的循环,因为它是最明显的答案。

perhaps a: 也许是:

i=2
while i < n:
    if something:
       do something
       i += 1
    else: 
       do something else  
       i = 2 #restart the loop  

Changing the index variable i from within the loop is unlikely to do what you expect. 从循环内更改索引变量i不太可能达到预期效果。 You may need to use a while loop instead, and control the incrementing of the loop variable yourself. 您可能需要使用while循环,并自己控制循环变量的递增。 Each time around the for loop, i is reassigned with the next value from range() . 每次围绕for循环, i都会重新分配来自range()的下一个值。 So something like: 所以类似于:

i = 2
while i < n:
    if(something):
        do something
    else:
        do something else
        i = 2 # restart the loop
        continue
    i += 1

In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. 在我的示例中, continue语句跳回到循环的顶部,跳过该迭代的i += 1语句。 Otherwise, i is incremented as you would expect (same as the for loop). 否则, i会按照您的预期递增(与for循环相同)。

Here is an example using a generator's send() method : 以下是使用生成器的send()方法的示例:

def restartable(seq):
    while True:
        for item in seq:
            restart = yield item
            if restart:
                break
        else:
            raise StopIteration

Example Usage: 用法示例:

x = [1, 2, 3, 4, 5]
total = 0
r = restartable(x)
for item in r:
    if item == 5 and total < 100:
        total += r.send(True) 
    else:
        total += item

Just wanted to post an alternative which might be more genearally usable. 只是想发布一个可能更普遍可用的替代方案。 Most of the existing solutions use a loop index to avoid this. 大多数现有解决方案使用循环索引来避免这种情况。 But you don't have to use an index - the key here is that unlike a for loop, where the loop variable is hidden, the loop variable is exposed. 但是你不必使用索引 - 这里的关键是与for循环不同,循环变量被隐藏,循环变量被暴露。

You can do very similar things with iterators/generators: 您可以使用迭代器/生成器执行非常类似的操作:

x = [1,2,3,4,5,6]
xi = iter(x)
ival = xi.next()
while not exit_condition(ival):
    # Do some ival stuff
    if ival == 4:
        xi = iter(x)
    ival = xi.next()

It's not as clean, but still retains the ability to write to the loop iterator itself. 它不是那么干净,但仍然保留了写入循环迭代器本身的能力。

Usually , when you think you want to do this, your algorithm is wrong, and you should rewrite it more cleanly. 通常 ,当您认为要执行此操作时,您的算法是错误的,您应该更干净地重写它。 Probably what you really want to do is use a generator/coroutine instead. 你真正想要做的就是使用生成器/协同程序。 But it is at least possible. 但这至少是可能的。

a = ['1', '2', '3']
ls = []
count = False

while ls != a :
    print(a[count])
    if a[count] != a[-1] :
        count = count + 1
    else :
        count = False

Restart while loop. 循环时重启。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM