SoFunction
Updated on 2024-11-17

Summary of Python's ideas for interrupting multiple loops

I. Jumping out of a single cycle

Regardless of the programming language, there may be a need to jump out of a loop, such as when enumerating, and terminating when you find a number that satisfies a condition. Jumping out of a single loop is simple, for example:

for i in range(10):

  if i > 5:

    print i

    break

However, we sometimes need to jump out of multiple loops, and break is only able to jump out of one layer of the loop, for example:

for i in range(10):

  for j in range(10):

    if i+j > 5:

      print i,j

      break

Such code does not mean that it stops when it finds a set i+j > 5, but that it finds 10 sets in a row, because break only jumps out of the for j in range(10) loop. So, how can I jump out of the multiple? Here is a memo.

II. Jumping out of multiple loops

In fact, Python's standard syntax doesn't support jumping out of multiple loops, so you have to utilize a few tricks, roughly along the lines of writing as a function, utilizing Cartesian products, and utilizing debugging.

Of course the most common way of thinking about this is to use the variable labeling method

def f():

  flag = 0

  for i in range(10):

    for j in range(i):

      if i+j>5:

        print i,j

        flag = 1

        break

    if flag == 1:

      break

if __name__ == "__main__":

  f()

Write as a function

In Python, a function runs to the phrase return and stops, so you can take advantage of this feature by writing the function as a function that terminates multiple loops.

Example:

def work():

  for i in range(10):

    for j in range(10):

      if i+j > 5:

        return i,j

print work()

Using the Cartesian product

The idea of this approach is that since I can jump out of a single loop, I rewrite the multiple loops as a single loop, which can be done using the Cartesian product function product in itertools, for example:

from itertools import product

for i,j in product(range(10), range(10)):

  if i+j > 5:

    print i,j

    break

Utilizing debug mode

The Cartesian product approach is clever and concise, but it can only be used in situations where the set of each loop is independent; if each layer of the loop is closely related to the previous layer, you can't use this technique. This time you can use the first method, it will be written as a function, in addition, you can also use debug mode. This one utilizes the principle of debugging mode, which exits whenever an error is reported, and it fakes an error out.

class Found(Exception):

  pass

try:

  for i in range(10):

    for j in range(i): # The second loop is related to the first

      if i + j > 5:

        raise Found

except Found:

  print i, j

Above is the inventory Python interrupt multiple loop ideas in detail, more please pay attention to my other related articles!