繁体   English   中英

突破嵌套而True循环

[英]Breaking out of nested while True loop

我正在运行一段while True:在webscraping脚本中循环。 我希望刮刀在增量循环中运行,直到遇到某个错误。 一般的问题是如何在某个条件匹配时突破一段时间的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]

你不需要tryexcept这里。 让事情变得简单,只需使用一个简单的while条件对你的go变量。 在这种情况下,您甚至不需要break因为只要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

替代消磨 :由于@chepner建议,你甚至都不需要while并用在更好的循环go

for r in runs:
    for go in range(1, 4):
        output = ("output " + str(r) + ";" +str(go))
        print(output)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM