简体   繁体   English

如果内部循环内的条件为真,则几个嵌套的'for'循环继续下一次外循环迭代

[英]Several nested 'for' loops, continue to next iteration of outer loop if condition inside inner loop is true

I know it is terribly inefficient and ugly code, but if I have three for loops, nested inside each other such as so: 我知道这是非常低效和丑陋的代码,但如果我有三个for循环,嵌套在彼此内部,如:

for x in range(0, 10):
    for y in range(x+1, 11):
       for z in range(y+1, 11):
           if ...

I want to break the two inner loops and continue to the next iteration of the outer loop if the if statement is true. 如果if语句为true,我想打破两个内部循环并继续外循环的下一次迭代。 Can this be done? 可以这样做吗?

Check some variable after each loops ends: 每个循环结束后检查一些变量:

for x in range(0, 10):
    for y in range(x+1, 11):
        for z in range(y+1, 11):
            if condition:
                variable = True
                break
            #...
        if variable:
            break;
        #...

Another option is to use exceptions instead of state variables: 另一种选择是使用异常而不是状态变量:

class BreakException(Exception):
    pass

for x in range(0, 10):
    try:
        for y in range(x+1, 11):
           for z in range(y+1, 11):
               if True:
                   raise BreakException
    except BreakException:
        pass

I imagine this could be especially useful if bailing out of more than two inner loops. 我想如果从两个以上的内环中拯救出来,这可能会特别有用。

n = False
for x in range(0,10):
    if n == True:
        print(x,y,z)
    for y in range(x+1, 11):
        if n == True:
            break
        for z in range(y+1, 11):
            if z == 5:
                n = True
                break

(1, 2, 5)
(2, 2, 5)
(3, 3, 5)
(4, 4, 5)
(5, 5, 5)
(6, 6, 5)
(7, 7, 5)
(8, 8, 5)
(9, 9, 5)

A possible solution is to merge the two inner loops to a single one (that can be terminated with break ): 一种可能的解决方案是将两个内部循环合并为一个(可以使用break终止):

import itertools

for x in range(10):
    for y, z in itertools.combinations(range(x+1, 11), 2):
        if condition:
            break

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

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