Python builtin “all” with generators

后端 未结 5 857
太阳男子
太阳男子 2020-12-18 07:07

I have the following problem with python\'s \"all\" and generators:

G = (a for a in [0,1])
all(list(G))   # returns False - as I expected

B

5条回答
  •  醉酒成梦
    2020-12-18 07:48

    Aha!

    Does Python(x,y) happen to import numpy? [It looks like it.]

    Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
    [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 
    >>> 
    >>> G = (a for a in [0,1])
    >>> all(G)
    False
    >>> from numpy import all
    >>> 
    >>> G = (a for a in [0,1])
    >>> all(G)
    True
    >>> 
    

    Here's an explanation by Robert Kern:

    It [all --ed] works on arrays and things it can turn into arrays by calling the C API equivalent of numpy.asarray(). There's a ton of magic and special cases in asarray() in order to interpret nested Python sequences as arrays. That magic works fairly well when we have sequences with known lengths; it fails utterly when given an arbitrary iterator of unknown length. So we punt. Unfortunately, what happens then is that asarray() sees an object that it can't interpret as a sequence to turn into a real array, so it makes a rank-0 array with the iterator object as the value. This evaluates to True.

提交回复
热议问题