python - 打破嵌套循环的缩进

标签 python loops nested break

我在嵌套 for 循环中断方面遇到了麻烦。

进一步的代码假设找到特定颜色的像素,该示例包含在打开的文件中,步骤 50沿x20沿y :

im1 = Image.open("C:\\Users\\Poos\\Desktop\\G\\green_pixel.bmp")
A = list(im1.getdata())

x = 0
y = 0

im2 = ImageGrab.grab()
B = list(im2.getdata())

for x in range(0,1024, 50):
    for y in range(0,600, 20):
      if(B != A):
         im3 = im2.crop((x,y,x+1,y+1))
         B = list(im3.getdata())
         print(x, y)

      else:
         print("hooray!")
         break

      break

一旦检测到像素,两个循环就会中断,并打印一些文本。

但是 x-loop 不会在外部中断所在的位置中断,从而多次打印我的文本。

似乎我已经尝试了外部中断位置的所有可能变体,但没有任何效果。

这里有什么问题吗?

最佳答案

考虑将代码放入函数中,并使用 return 语句来打破所有循环。

def func():
    im1 = Image.open("C:\\Users\\Poos\\Desktop\\G\\green_pixel.bmp")
    A = list(im1.getdata())

    x = 0
    y = 0

    im2 = ImageGrab.grab()
    B = list(im2.getdata())

    for x in range(0,1024, 50):
        for y in range(0,600, 20):
        if(B != A):
            im3 = im2.crop((x,y,x+1,y+1))
            B = list(im3.getdata())
            print(x, y)

        else:
            print("hooray!")
            return

        return

关于python - 打破嵌套循环的缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33318316/

相关文章:

python - 值错误 : No Shapely geometry can be created from null value

loops - 双循环函数的时间复合体

循环内的 JavaScript 闭包 – 简单的实际示例

javascript - 在 es6 中创建多维映射数组

python - GRU 和 RNN 实现之间的不一致

python - 数据单位的行上限长度是多少?

node.js - Mongoose :Find and filter nested array

c# - Automapper - 无法映射嵌套对象/集合

python - Windows 上的子进程未收到信号 (SIGTERM)

arrays - 如何使用 Template Toolkit 访问数组的元素?