如果使用生成器表达式,为什么Numpy.all()和any()给出错误的结果? [英] Why do Numpy.all() and any() give wrong results if you use generator expressions?
问题描述
使用其他人的代码时,我偶然发现了这个陷阱.那么,对numpy行为的解释是什么?
Working with somebody else's code I stumbled across this gotcha. So what is the explanation for numpy's behavior?
In [1]: import numpy as np
In [2]: foo = [False, False]
In [3]: print np.any(x == True for x in foo)
True # <- bad numpy!
In [4]: print np.all(x == True for x in foo)
True # <- bad numpy!
In [5]: print np.all(foo)
False # <- correct result
p.s.我从这里获得了列表理解代码:检查列表是否仅包含项x
p.s. I got the list comprehension code from here: Check if list contains only item x
推荐答案
np.any
和np.all
在生成器上不起作用.他们需要序列.当给定非序列时,他们将其视为任何其他对象,并在其上调用bool
(或执行等效操作),这将返回True
:
np.any
and np.all
don't work on generators. They need sequences. When given a non-sequence, they treat this as any other object and call bool
on it (or do something equivalent), which will return True
:
>>> false = [False]
>>> np.array(x for x in false)
array(<generator object <genexpr> at 0x31193c0>, dtype=object)
>>> bool(x for x in false)
True
列表理解有效,但是:
>>> np.all([x for x in false])
False
>>> np.any([x for x in false])
False
我建议在需要生成器时使用Python内置的any
和all
,因为它们通常比使用NumPy和列表理解要快(由于两次转换,首先是转换为list
,然后转换为
I advise using Python's built-in any
and all
when generators are expected, since they are typically faster than using NumPy and list comprehensions (because of a double conversion, first to list
, then to array
).
这篇关于如果使用生成器表达式,为什么Numpy.all()和any()给出错误的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!