Stopping an iteration without using `break` in Python 3

后端 未结 4 1435
春和景丽
春和景丽 2021-01-20 12:02

For example, can this code be rewritten without break (and without continue or return)?

import logging

for i, x in en         


        
4条回答
  •  面向向阳花
    2021-01-20 12:21

    You could use a boolean value to check if you are done. It will still iterate the rest of the loop but not execute the code. When it is done it will continue on its way without a break. Example Pseudo code below.

    doneLogging = False
    for i, x in enumerate(x):
        if not doneLogging:
            logging.info("Processing `x` n.%s...", i)
            y = do_something(x)
            if y == A:
                logging.info("Doing something else...")
                do_something_else(x)
            elif y == B:
                logging.info("Done.")
                doneLogging = True
    

提交回复
热议问题