检查什么理解列表输出不是None并转到相应的功能

Check what comprehension list output is not None and go to the corresponding function

我正在对理解列表进行一些试验,想知道是否可以检查找到了什么图像(只能找到 1 张)并将程序发送到具有该数字正确代码的函数。所以程序应该检查哪个输入不是None,并在相应的函数中继续。

def one():
    #the program should go here if image one.png is detected
def two():
    #the program should go here if image two.png is detected
def three():
    #the program should go here if image three.png is detected
def four():
    #the program should go here if image four.png is detected

number = [pyautogui.locateOnScreen(f'{nr}.png', confidence = 0.95)
                for nr in ('one', 'two', 'three', 'four')
            ]

如果这些函数是 class.

的方法,则有一种方法
import os


class A:
  def one():
    #the program should go here if image one.png is detected
  def two():
    #the program should go here if image two.png is detected
  def three():
    #the program should go here if image three.png is detected
  def four():
    #the program should go here if image four.png is detected


a = A()
number = "one.png"
func_name = os.path.splitext(number)[0] # Remove .png extension
f = getattr(a, "func_name")

f()

函数是对象,就像 Python 中的任何其他对象一样。这就是为什么你可以创建一个字典,例如

images = {"one": one, "two": two, "three": three, "four": four}

等等,如果你设法将找到的图像的名称放入某个变量中,例如 image_name,你可以将其称为

images[image_name]()

这将执行所需的功能。

所以总而言之你会

images = {"one": one, "two": two, "three": three, "four": four}

number = [nr for nr in ('one', 'two', 'three', 'four') if 
          pyautogui.locateOnScreen(f'{nr}.png', confidence = 0.95) is not None][0]

images[number]()

注意列表推导后的 [0],因为我们需要名称,而不是列表中的名称,最后一行末尾的 () 表示我们正在调用对象(在我们的例子中是函数)。

pyautogui.locateOnScreen() 不 return None 当没有找到匹配时,它会引发 ImageNotFoundException,当它找到匹配时它会 return 是在屏幕上找到的第一个图像实例的(左、上、宽、高)信息,而不是图像名称。换句话说,在我看来,在这种情况下使用列表理解并没有多大意义。

你可以利用字典的值可以是任何东西这一事实来简化事情,包括函数对象,这使得在给定图像名称的情况下查找它们变得非常容易。还定义了一个调用 pyautogui.locateOnScreen() 并抑制它在没有匹配项时引发的异常的中间函数,以便为 pyautogui 的函数提供更方便的接口。

import pyautogui


def one():
    print('image one.png detected')
def two():
    print('image two.png detected')
def three():
    print('image three.png detected')
def four():
    print('image four.png detected')


image_functions = {"one": one, "two": two, "three": three, "four": four}

def check_image_on_screen(image_name):
    try:
        location = pyautogui.locateOnScreen(f'{nr}.png', confidence=0.95)
    except ImageNotFoundException:
        location = None
    if location:
        return image_name


for nr in ('one', 'two', 'three', 'four'):
    func = image_functions.get(check_image_on_screen(nr), None)
    if func:
        func()
        break
else:
    print('No image detected')