给定以下代码(不起作用):
while True:
# Snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok.lower() == "y": break 2 # This doesn't work :(
if ok.lower() == "n": break
# Do more processing with menus and stuff
有办法解决这个问题吗?还是我必须先检查一次,跳出输入循环,然后再检查一次,如果用户满意,再跳出外部循环?
将循环逻辑分解为迭代器,迭代器产生循环变量并在完成时返回——这里有一个简单的迭代器,它将图像按行/列排列,直到我们用完图像或找不到放置它们的位置:
def it(rows, cols, images):
i = 0
for r in xrange(rows):
for c in xrange(cols):
if i >= len(images):
return
yield r, c, images[i]
i += 1
for r, c, image in it(rows=4, cols=4, images=['a.jpg', 'b.jpg', 'c.jpg']):
... do something with r, c, image ...
这样做的优点是将复杂的循环逻辑和处理分开。
解决方法有两种
举个例子:这两个矩阵相等/相同吗?
矩阵x1和矩阵x2是相同大小的,n,二维矩阵。
第一个解决方案,没有函数
same_matrices = True
inner_loop_broken_once = False
n = len(matrix1)
for i in range(n):
for j in range(n):
if matrix1[i][j] != matrix2[i][j]:
same_matrices = False
inner_loop_broken_once = True
break
if inner_loop_broken_once:
break
第二个解决方案,用函数
这是我案子的最终解决方案。
def are_two_matrices_the_same (matrix1, matrix2):
n = len(matrix1)
for i in range(n):
for j in range(n):
if matrix1[i][j] != matrix2[i][j]:
return False
return True
Break for外层和内部while循环:
while True:
while True:
print('Breaks inner "while" loop')
break # Here
print('Breaks outer "while" loop')
break # Here
或者,用if语句中断外部和内部while循环:
while True:
while True:
if True:
print('Breaks inner "while" loop')
break # Here
print('Breaks outer "while" loop')
break # Here
输出:
Breaks inner "while" loop
Breaks outer "while" loop
Break for outer和inner for循环:
for _ in iter(int, 1):
for _ in iter(int, 1):
print('Breaks inner "for" loop')
break # Here
print('Breaks outer "for" loop')
break # Here
或者,用if语句打破外部和内部for循环:
for _ in iter(int, 1):
for _ in iter(int, 1):
if True:
print('Breaks inner "for" loop')
break # Here
print('Breaks outer "for" loop')
break # Here
输出:
Breaks inner "for" loop
Breaks outer "for" loop