首页 > 解决方案 > 检查哪些理解列表输出不是 None 并转到相应的功能

问题描述

我正在对理解列表进行一些试验,并想知道是否可以检查找到了什么图像(只能找到 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')
            ]

标签: pythonlist-comprehension

解决方案


函数是对象,就像 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]列表推导之后,因为我们想要名称,而不是列表中的名称,以及()最后一行末尾的 ,表明我们正在调用对象(在我们的例子中是函数)。


推荐阅读