python - 检查哪些理解列表输出不是 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')
]
解决方案
函数是对象,就像 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]
列表推导之后,因为我们想要名称,而不是列表中的名称,以及()
最后一行末尾的 ,表明我们正在调用对象(在我们的例子中是函数)。
推荐阅读
- r - if ((!is.matrix(model)) | ncol(model) != 3) stop("model argument must be a 3-column matrix") 中的错误
- scala - Spark迭代程序具有线性内存消耗
- javascript - 当数据仅返回布尔值时,如何编写 graphql-tag?
- angular - ng slim loader 在点击链接时重复 3 次
- python - 如何删除由我的 python 代码创建的所有 pandas 数据框
- xamarin - Xamarin.forms iOS 模拟器未启动
- javascript - 在 JavaScript 中实现枚举的最佳方式是什么?
- javascript - 如何修复在 ReactSwing Api 中被忽略的 setState 钩子?
- python - 为什么 tkinter 程序没有显示任何文本?
- java - 无法在流 java 中的 forEach 循环内打印