打破嵌套循环和迭代

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

这是我的代码的简单结构:

while condition:
    for i in range(num):
        for j in range(num):
            if arr[i][j] == something:
                #DO SOMETHING
                #ESCAPE 

我只想转义 for 循环并从 while 循环内的 arr[0][0] 开始迭代。

它还必须避免检查与上一个循环中检查的相同值。

例如,如果 arr[1][1] == some ,那么它会跳过 if 语句,对于下一次迭代,它应该再次从 arr[0][0] 开始并跳过检查 arr[1][1] .

我正在努力处理break语句和跳过部分。

python nested-loops break
1个回答
0
投票
checked_indices = set()  # Set to store the checked indices

while condition:
    for i in range(num):
        for j in range(num):
            if (i, j) not in checked_indices and arr[i][j] == something:
                # DO SOMETHING
                checked_indices.add((i, j))  # Add the checked index to the set
                break  # Escape the innermost for loop
        else:
            continue  # Continue to the next iteration of the outer for loop
        break  # Escape the outer for loop
    else:
        break  # Escape the while loop

# Continue with the rest of your code

checked_indices
集用于跟踪已检查的
indices
。如果索引
(i, j)
已经被检查过,它将在下一次迭代中被跳过。

© www.soinside.com 2019 - 2024. All rights reserved.