python - 打破嵌套的while True循环
问题描述
我while True:
在网页抓取脚本中运行一个循环。我希望刮板以增量循环运行,直到遇到某个错误。一般问题是关于当某个条件匹配时如何跳出while True循环。代码只是永远输出第一次运行:
output 1;1
...
output 1;n
这是我的代码的最小可重现示例。
runs = [1,2,3]
for r in runs:
go = 0
while True:
go +=1
output = ("output " + str(r) + ";" +str(go))
try:
print(output)
except go > 3:
break
所需的输出是:
output 1;1
output 1;2
output 1;3
output 2;1
output 2;2
output 3;3
output 3;1
output 3;2
output 3;3
[done]
解决方案
你不需要try
和except
这里。保持简单,只需对变量使用简单的while
条件。go
在这种情况下,您甚至不需要 abreak
因为只要go>=3
条件为False
,您将退出 while 循环并重新启动 while 循环以获取 的下一个值r
。
runs = [1,2,3]
for r in runs:
go = 0
while go <3:
go +=1
output = ("output " + str(r) + ";" +str(go))
print(output)
输出
output 1;1
output 1;2
output 1;3
output 2;1
output 2;2
output 2;3
output 3;1
output 3;2
output 3;3
while 的替代方案:正如@chepner 所建议的那样,您甚至不需要while
并且最好使用 for 循环go
作为
for r in runs:
for go in range(1, 4):
output = ("output " + str(r) + ";" +str(go))
print(output)
推荐阅读
- javascript - 当在 useEffect() 中触发 socket.on() 时,反应状态被设置回初始 []
- ansible - 在评估条件时(argoProj.stdout.find('xcore')!= -1):'dict object'没有属性'stdout'
- powershell - Powershell命令在每个文件之前添加文本
- python - How to apply a function/impute on an interval in Pandas
- json - 参数覆盖:'TypeError: Cannot read property 'type' of undefined',确保它遵循 JavaScript Object Notation (JSON)
- c++ - 在单个 for 循环中检查和替换重复项
- react-native - 从背景颜色 a 到 b 的 react-native 渐变
- java - 无法在 listview java 中显示来自 json 的数据,并且不推荐使用 android.os.asynctask
- c# - 发送网格发送电子邮件的 System.Net.Http.HttpRequestException
- webpack - 用于渲染地图的 ArcGIS webpack 插件,未找到模块:错误:无法解析“esri/地图”