本文介绍了在Python 3中停止迭代而不使用`break'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,这个代码可以被重写,而不需要你可以使用一个函数并返回它:
导入记录
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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!