嵌套 Python For 循环中 continue 的范围是什么?

问题描述 投票:0回答:3

使用嵌套 for 循环时,如果我在内层嵌套 for 循环中使用 continue ,那么 continue 的作用域仅适用于内循环还是会继续外循环?

注意:对于我正在做的事情,我只想继续影响嵌套循环

b = ["hello"] * 5
d = ["world"] * 10

for a in b: # Outer Loop
    x = 1 + 1
    for c in d: # Nested Loop
        if c:
            x += 1
        else: 
            continue # Does this affect the Nested Loop or the Outer Loop
python for-loop scope nested continue
3个回答
10
投票

它只影响内循环。


3
投票

循环控制关键字(如

break
continue
)仅影响范围内最接近它们的循环。因此,如果您有一个循环嵌套在另一个循环中,则关键字的目标是它紧邻的任何循环,而不是更远的循环。


0
投票

正如@botiapa所说:它只影响内部循环。

现在,如果您想制定一个工作流程来影响上层范围循环,您有 2 个解决方案:

1 - 在上层作用域循环的顶部使用变量:

b = ["hello"] * 5
d = ["world"] * 10

for a in b: # Outer Loop

    outer_loop_should_break = False
    
    x = 1 + 1
    for c in d: # Nested Loop
        if c:
            x += 1
        else:
            outer_loop_should_break = True
            break # Does this affect the Nested Loop
     
     if outer_loop_should_break:
         break
     else:
         # do something

2 - 使用异常以获得更好的跟踪:

class ShouldBreak(Exception):
    pass

class ShouldContinue(Exception):
    pass

b = ["hello"] * 5
d = ["world"] * 10

for a in b: # Outer Loop
    x = 1 + 1
    try:
        for c in d: # Nested Loop
            if c:
                x += 1
            else:
                raise ShouldBreak("explain why")
                # Or
                raise ShouldContinue("explain why")

    except ShouldBreak as sb:
        print(str(sb))
        break
    except ShouldContinue as sc:
        print(str(sc))
        continue
     
     # do something else after

如果您确实想在循环中使用命名空间,您可以切换到 JavaScript 并在循环上使用标签:此处的文档

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.