Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

python - numpy all differing from builtin 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Numpy.all does not understands generator expressions.

From the documentation

 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

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

From the documentation of 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

Finally, trying

>>> np.asarray(0 for i in range(10))
array(<generator object <genexpr> at 0x42740828>, dtype=object)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...