numpy的这种奇怪之处是什么原因all
?
>>> import numpy as np
>>> np.all(xrange(10))
False
>>> np.all(i for i in xrange(10))
True
Run Code Online (Sandbox Code Playgroud)
Numpy.all不了解生成器表达式.
从文档中
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.
Run Code Online (Sandbox Code Playgroud)
好的,不是很明确,所以让我们看看代码
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
Run Code Online (Sandbox Code Playgroud)
作为发电机表达式不具有all
的方法,它结束调用_wrapit
在_wrapit
为,它首先检查__array_wrap__
方法,其generates AttributeError
最后结束了呼叫asarray
在发电机表达
从文档中 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.
Run Code Online (Sandbox Code Playgroud)
有关所接受的各种类型的输入数据的详细记录,绝对不是生成器表达式
最后,尝试
>>> np.asarray(0 for i in range(10))
array(<generator object <genexpr> at 0x42740828>, dtype=object)
Run Code Online (Sandbox Code Playgroud)