Why do Numpy.all() and any() give wrong results if you use generator expressions?

前端 未结 1 1757
迷失自我
迷失自我 2020-12-11 04:25

Working with somebody else\'s code I stumbled across this gotcha. So what is the explanation for numpy\'s behavior?

In         


        
相关标签:
1条回答
  • 2020-12-11 05:04

    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
    

    List comprehensions work, though:

    >>> np.all([x for x in false])
    False
    >>> np.any([x for x in false])
    False
    

    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).

    0 讨论(0)
提交回复
热议问题