繁体   English   中英

在Python 3中不使用`break`来停止迭代

[英]Stopping an iteration without using `break` in Python 3

例如,可以在此代码,而无需重写break (并且没有continuereturn )?

import logging

for i, x in enumerate(x):
    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.")
        break

编辑:由于有些人批评使用breakcontinue内部循环,我想知道Python是否允许在没有它们的情况下编写for循环。 我会说Python不允许这样做(也许它会违背“一种方法”规则)。

编辑2:评论者让我注意到可以使用return ,但这也不是解决方案。

你总是可以使用一个函数并从中返回:

import logging

def func():
    for i, x in enumerate(x):
        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.")
            return # Exit the function and stop the loop in the process.
func()

虽然在我看来使用break更优雅,因为它让你的意图更清晰。

您可以使用布尔值来检查是否已完成。 它仍将迭代循环的其余部分但不执行代码。 一旦完成,它将继续前进而不会中断。 示例下面的伪代码。

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

你也可以使用sys.exit()

import logging
import sys

for i, x in enumerate(x):
    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.")
        sys.exit(0)

breakcontinue关键字只在循环中有意义,而在其他地方它们是一个错误。

for grooble in spastic():
    if hasattr(grooble, '_done_'):
        # no need for futher processing of this element
        continue
    elif grooble is TheWinner:
        # we have a winner!  we're done!
        break
    else:
        # process this grooble's moves
        ...

任何不打算使用breakcontinue都不会教好Python。

暂无
暂无

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

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