I know it is terribly inefficient and ugly code, but if I have three for
loops, nested inside each other such as so:
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. 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
):
import itertools
for x in range(10):
for y, z in itertools.combinations(range(x+1, 11), 2):
if condition:
break
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.