为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

三国纷争 2021-11-16 10:53:06
好的,所以我有这个脚本,它只点击具有某种灰色阴影的像素,除了一件事之外,它在大多数情况下都可以正常工作,它循环太长,每次我应该如何更改大约需要一秒钟在我找到一个有效像素后,我的休息会更好地工作并阻止它四处循环?xx = 0while 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)
查看完整描述

2 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

如果在内循环中没有找到有效像素(因此没有发生),您可以使用该for-else构造,continue如果找到了,则可以使用外循环:breakbreak


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


查看完整回答
反对 回复 2021-11-16
?
BIG阳

TA贡献1859条经验 获得超6个赞

免责声明:我不熟悉 mss。你可以改进的几件事:


无需枚举您不感兴趣的值。您可以这样做:

for row, pxl in enumerate(pxls, start=378):

    if row > 530:

       break

    for col, pxll in enumerate(pxl, start=71):

        if col > 328:

           break

你不能只截取所需区域的屏幕截图吗?这样的事情应该有效吗?

region = {'top': 378, 'left': 71, 'width': 328-71, 'height': 530-378}

您正在使用双 python 循环操作二维数组。您可以使用一些旨在对数组执行操作的模块,并且速度可以提高几个数量级。像 Pandas 或 NumPy 这样的东西应该能够几乎立即运行。


查看完整回答
反对 回复 2021-11-16
  • 2 回答
  • 0 关注
  • 160 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信