Stopping an iteration without using `break` in Python 3(在 Python 3 中不使用“break就停止迭代)
问题描述
例如,这段代码可以在没有break(并且没有continue或return)的情况下重写吗?
For example, can this code be rewritten without break (and without continue or return)?
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
由于有些人批评在循环中使用 break 和 continue,我想知道 Python 是否允许编写 for 循环而不使用他们.我会说 Python 不允许这样做(也许它会违反一种方法"的规则).
Since some people criticize the use of break and continue inside loops, I was wondering whether Python allowed to write for loops without them. I would say that Python doesn't allow this (and maybe it would go against the "one way to do it" rule).
评论者让我注意到可以使用 return 代替,但这也不是解决方案.
Commenters have made me notice that return could be used instead, but that would not be a solution, either.
推荐答案
你总是可以使用一个函数并从它返回:
You could always use a function and return from it:
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 更优雅,因为它让你的意图更清晰.
Although using break is more elegant in my opinion because it makes your intent clearer.
这篇关于在 Python 3 中不使用“break"就停止迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 3 中不使用“break"就停止迭代
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
