提问人:Softly 提问时间:9/2/2023 最后编辑:John KugelmanSoftly 更新时间:9/2/2023 访问量:59
打破嵌套循环和迭代 [duplicate]
Breaking nested loops and iteration [duplicate]
问:
所以这是我的代码的简单结构:
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] == something 所以它会遍历 if 语句,那么在下一次迭代中,它应该再次从 arr[0][0] 开始并跳过检查 arr[1][1]。
我正在为中断语句和跳过部分而苦苦挣扎。
答:
-1赞
Sauron
9/2/2023
#1
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
set 用于跟踪已检查的内容。如果已检查索引,则将在下一次迭代中跳过该索引。indices
(i, j)
break
语句用于在找到匹配项时转义 for 循环,并在必要时继续外部 for 循环或 while 循环的下一次迭代。
评论
2赞
B Remmelzwaal
9/2/2023
虽然这有效,但阅读和理解起来非常混乱。
评论