Python any()返回True,但是;是真的吗;比较失败
如果Python any()返回True,但是;是真的吗;比较失败,python,numpy,Python,Numpy,如果numpy.any()。有人知道为什么吗 最简单的例子 from __future__ import print_function import numpy a = numpy.array([True]) if a.any() == True: print('== works') if a.any() is True: print('is works') 这段代码的输出只是==worksnumpy有自己的布尔值,numpy.True\uu和numpy.False\ucode>
numpy.any()。有人知道为什么吗
最简单的例子
from __future__ import print_function
import numpy
a = numpy.array([True])
if a.any() == True:
print('== works')
if a.any() is True:
print('is works')
这段代码的输出只是==works
numpy
有自己的布尔值,numpy.True\uu和numpy.False\ucode>与Python的本机布尔值具有不同的标识。无论如何,您应该使用==
进行此类权益比较
>>> a.any() is True
False
>>> a.any() is numpy.True_
True
>>> True is numpy.True_
False
>>> True == numpy.True_
True
返回的类型不同:
>>> type(a.any())
<type 'numpy.bool_'>
>>> type(True)
<type 'bool'>
>类型(a.any())
>>>类型(真)
因此,a.any()本身不是True
,它只等于True
,这是因为a.any()
不返回标准PythonTrue
(类bool
的实例)
>类型(a.any())
简而言之,numpy有它自己的真值,但当您打印它时,它看起来就像Python内置的True
返回一个numpy.bool
,这是numpy使用的
因此,不能使用身份检查将numpy.bool\ucode>与Pythonbool
进行比较。您必须使用numpy的true
然后:numpy.true
>>> a.any() is numpy.True_
True
他们不使用Python的bool
的主要原因是因为numpy.bool
只是一个字节,而Pythonbool
是基于Pythonint
的,而int
总是比较昂贵。你为什么要使用is
进行这种比较?出于同样的原因,1==1.0
为True
,1为1.0
为False
。1是整数,1.0是浮点。两件事可以是等价的,但有不同的底层结构。谢谢,就是这样!我应该检查一下类型。谢谢实际上,根本不检查布尔等式。只要做如果a.any()
或者如果不是a.any()
@poke timgeb是的,当然,在这个特定的布尔上下文中,我的意思是,一般来说,公平检查比身份检查更可取(除非你实际上试图检查身份)numpy
也有numpy.bool
,这是Python的原生版本,我猜遗留版本会产生一些奇怪的东西
>>> a.any() is numpy.True_
True