在Python 3中停止迭代而不使用`break' [英] Stopping an iteration without using `break` in Python 3
问题描述
例如,这个代码可以被重写,而不需要 break
(也可以不用 continue 或
返回
)?
导入记录
用于i,x用于枚举(x):
logging.info(Processing`x`n。%s ...,i)
y = do_something(x)
if y == A:
。logging.info(做别的...)
do_something_else(x)
elif y == B:
logging.info(Done。)
break
编辑:既然有人批评使用 break
和 continue
内部循环,我想知道Python是否允许为没有它们的循环写循环。我会说,Python不允许这样做(也许这将违背一种做法规则)。
编辑2:评论者让我注意到可以使用 return
来代替,但这也不是一个解决方案。
导入记录
def func():
for i,x in enumerate(x):
logging.info(Processing`x`n。%s ...,i)
y = do_something x)
if y == A:
logging.info(做别的...)
do_something_else(x)
elif y == B:
logging.info(完成)
return#退出函数并停止进程中的循环。
func()
尽管使用 break
在我看来更优雅,因为它使你的意图更清晰。
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
EDIT: 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).
EDIT2: 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()
Although using break
is more elegant in my opinion because it makes your intent clearer.
这篇关于在Python 3中停止迭代而不使用`break'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!