为什么python在下面的代码中显示(32 == 0)
当我测试以下代码时给出了一个奇怪的结果
while not stop:
results = pyautogui.locateAllOnScreen('background data/test.png', confidence = 0.9)
print(len(list(results)))
print(len(list(results)) == 0)
if len(list(results)) == 0:
print('exit loop')
break
Run Code Online (Sandbox Code Playgroud)
上面代码的结果是
32
True
exit loop
Run Code Online (Sandbox Code Playgroud)
len(list(results))给出 的输出32: int,但与 比较时0: int,返回 True
小智 7
pyautogui.locateAllOnScreen返回一个生成器,您在最初打印长度时会耗尽该生成器。要解决此问题,请转换results为列表或删除调试语句。
这就是正在发生的事情:
# results is a generator like below
results = (i for i in range(2))
# by calling list on the generator, we consume/exhaust it.
print(len(list(results)))
# output: 2
# if we try to consume again, the generator is empty
print(len(list(results)) == 0)
# output: True, as the len(list(results)) is 0
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
# create a generator again
results = (i for i in range(2))
# consume it by converting generator to list once
results_list = list(results)
print(len(results_list))
# output: 2
print(len(results_list) == 0)
# output: False, as the len(results_list) is 2
Run Code Online (Sandbox Code Playgroud)