为什么Python的`any`函数不会返回True或False? [英] Why does Python's `any` function not return True or False?

查看:163
本文介绍了为什么Python的`any`函数不会返回True或False?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试

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

它不返回TrueFalse.

返回

<generator object <genexpr> at 0x7fbd62129ab0>

推荐答案

您正在使用numpy.any()而不是内置的any().您最有可能具有from numpy import anyfrom numpy import *,这会导致此行为.

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.

为什么会这样?

根据文档any测试是否有任何元素评估条件.但是,如果您查看源代码,它实际上会返回asanarray()结果,即generator.

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.

如何避免?

总是只导入scope而不是方法本身是个好主意,例如:import numpy as np

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

:)

更新1

我个人从未使用过iPython,但是由于@Praveen和@hpaulj的评论,如果将--pylab标志与ipython一起使用,您将看到相同的行为,并且可以关闭该行为. -从来不知道! :)))

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! :)))

这篇关于为什么Python的`any`函数不会返回True或False?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆