我在 while 循环中的 python 中有两个 for 循环,如下所示:while .. for .. for .. if condition == True: break一旦满足 if 语句中的条件,我想打破第一个 for 循环,我该如何实现,看来 break 只是终止内部 for 循环而不是外部循环,我希望终止外部 for 循环。
3 回答

慕田峪7331174
TA贡献1828条经验 获得超13个赞
使用标志通知外部断路器:
while ..
for ..
should_break = False
for ..
if condition == True:
should_break = True
break
if should_break: break

杨魅力
TA贡献1811条经验 获得超6个赞
不幸的是,我将用于 C 编程的解决方案,一个goto命令(讨厌的人会讨厌),在 Python 中不存在。
我也遇到过这种情况,我知道的最佳解决方案如下:
while ...
breakLoop = False
for ...:
for ...:
if condition:
breakLoop = True
break
if breakLoop:
break

MMTTMM
TA贡献1869条经验 获得超4个赞
我会尝试重构它,这样你就没有那么多嵌套循环了。也许将内部循环移动到一个函数中?否则,您也可以在内循环之后添加中断。
while ..
for ..
for ..
if condition == True:
break
if condition == True:
break
添加回答
举报
0/150
提交
取消