代码之家  ›  专栏  ›  技术社区  ›  Simon Lindgren

打破嵌套while True循环

  •  3
  • Simon Lindgren  · 技术社区  · 6 年前

    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]
    
    1 回复  |  直到 6 年前
        1
  •  6
  •   Sheldore    6 年前

    你不需要 try except 在这里保持简单,只需使用简单的 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
    

    替代while :正如@chepner所建议的,您甚至不需要 虽然 而且最好是用for循环结束

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