簡體   English   中英

更有效的嵌套循環中斷方法?

[英]More efficient breaking method for nested loops?

好的,所以我有這個腳本,它只點擊具有某種灰色陰影的像素,除了一件事外,它在大多數情況下都可以正常工作,它循環太長,每次我應該如何更改大約需要一秒鍾在我找到一個有效像素后,我的休息會更好地工作並阻止它四處循環?

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)

如果在內循環中沒有找到有效像素(因此沒有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

免責聲明:我不熟悉 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 循環操作二維數組。 您可以使用一些旨在對數組執行操作的模塊,並且速度可以提高幾個數量級。 像 Pandas 或 NumPy 這樣的東西應該能夠幾乎立即運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM