问题描述
numpy的all
出现这种怪异的原因是什么?
What is the reason for this weirdness in numpy's all
?
>>> import numpy as np
>>> np.all(xrange(10))
False
>>> np.all(i for i in xrange(10))
True
推荐答案
Numpy.all不理解生成器表达式.
Numpy.all does not understands generator expressions.
从文档中
numpy.all(a, axis=None, out=None)
Test whether all array elements along a given axis evaluate to True.
Parameters :
a : array_like
Input array or object that can be converted to an array.
好吧,不是很明确,所以让我们看一下代码
Ok, not very explicit, so lets look at the code
def all(a,axis=None, out=None):
try:
all = a.all
except AttributeError:
return _wrapit(a, 'all', axis, out)
return all(axis, out)
def _wrapit(obj, method, *args, **kwds):
try:
wrap = obj.__array_wrap__
except AttributeError:
wrap = None
result = getattr(asarray(obj),method)(*args, **kwds)
if wrap:
if not isinstance(result, mu.ndarray):
result = asarray(result)
result = wrap(result)
return result
由于生成器表达式没有all
方法,因此最终调用_wrapit
在_wrapit
中,它首先检查__array_wrap__
方法,该方法generates AttributeError
最后结束在生成器表达式上调用asarray
As generator expression doesn't have all
method, it ends up calling _wrapit
In _wrapit
, it first checks for __array_wrap__
method which generates AttributeError
finally ending up calling asarray
on the generator expression
来自numpy.asarray
numpy.asarray(a, dtype=None, order=None)
Convert the input to an array.
Parameters :
a : array_like
Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
关于接受的各种输入数据的文献充分记录,这绝对不是生成器表达式
It is well documented about the various types of Input data thats accepted which is definitely not generator expression
最后,尝试
>>> np.asarray(0 for i in range(10))
array(<generator object <genexpr> at 0x42740828>, dtype=object)
这篇关于numpy的所有不同于内置所有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!