Why does Python's `any` function not return True or False? [closed]

帅比萌擦擦* 提交于 2019-12-25 18:53:41

问题


If I try

>>> from pylab import *
>>> b = [2, 3, 4, 5, 6, 7]
>>> a = any(x < 0 for x in b)  
>>> print(a)

it doesn't return True or False.

It returns

<generator object <genexpr> at 0x7fbd62129ab0>

回答1:


You are using a numpy.any() instead of the built-in any(). Most probably you have from numpy import any or from numpy import *, which causes this behavior.

Why that happens?

According to the documentation, any tests if any element evaluates the condition. However, if you look into the source code, it actually returns a asanarray() result which is a generator.

How to avoid it?

It is always a good idea to import only scope rather than the method itself, like so: import numpy as np

:)

UPDATE 1

Personally, I have never used iPython, but thanks to comments by @Praveen and @hpaulj, if you use --pylab flag with ipython, you will see the same behavior, and you can turn that behavior off - never knew it! :)))




回答2:


it returns false

 >> b = [2,3,4,5,6,7]
 >>> b
 [2, 3, 4, 5, 6, 7]
 >>> a = any(x<0 for x in b)
 >>> a
 False
 >>> print(a)
 False


来源:https://stackoverflow.com/questions/39356081/why-does-pythons-any-function-not-return-true-or-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!