更有效的中断嵌套循环的方法?

2024-03-28 16:17:04 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我有这个脚本,它只点击像素有一定的灰色阴影,它的大部分工作正常,除了一件事,它循环太长,大约需要一秒钟来通过每次我该如何改变我的休息,以更好地工作,并阻止它从循环后,我发现了一个有效的像素?你知道吗

xx = 0
while xx <= 600:
    with mss.mss() as sct:
        region = {'top': 0, 'left': 0, 'width': 1920, 'height': 1080}
        imgg = sct.grab(region)
        pxls = imgg.pixels

        for row, pxl in enumerate(pxls):
            for col, pxll in enumerate(pxl):
                if pxll == (102, 102, 102):
                    if col>=71 and col<=328 and row<=530 and row>=378:
                        foundpxl = pxll
                        print(str(col) +" , "+ str(row))
                        pyautogui.click(col,row)
                        break
        xx = xx + 1
        time.sleep(.05)

Tags: andinforcol像素regionrowxx
2条回答

免责声明:我不熟悉mss。 您可以改进以下几点:

  1. 不需要列举你不感兴趣的值。你可以做:
for row, pxl in enumerate(pxls, start=378):
    if row > 530:
       break
    for col, pxll in enumerate(pxl, start=71):
        if col > 328:
           break
  1. 你就不能只拍下你想要的区域的截图吗?像这样的东西应该有用吗?你知道吗
region = {'top': 378, 'left': 71, 'width': 328-71, 'height': 530-378}
  1. 您正在使用双python循环操作2D数组。您可以使用一些设计用于对阵列执行操作的模块,并且可以快几个数量级。像熊猫或者小矮人这样的动物应该可以很快地运行它。你知道吗

如果在内环中找不到有效像素(因此没有出现break),则可以使用for-else构造来continue,如果找到有效像素,则可以使用break构造来外环:

for row, pxl in enumerate(pxls):
    for col, pxll in enumerate(pxl):
        if pxll == (102, 102, 102) and col >= 71 and col <= 328 and row <= 530 and row >= 378:
            foundpxl = pxll
            print(str(col) + " , " + str(row))
            pyautogui.click(col, row)
            break
    else:
        continue
    break

相关问题 更多 >