跳出嵌套while真循环

2024-09-27 04:27:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在webscraping脚本中运行while True:循环。我希望scraper以增量循环运行,直到遇到某个错误。一般的问题是当某个条件匹配时,如何跳出while真循环。原样的代码将永远输出第一次运行:

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]

Tags: 代码脚本truegoforoutput错误runs
1条回答
网友
1楼 · 发布于 2024-09-27 04:27:19

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

while的替代方法:正如@chepner所建议的,您甚至不需要while,最好使用go上的for循环

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

相关问题 更多 >

    热门问题