numpy.any()返回True但"是True"比较失败

flo*_*ren 3 python numpy

如果numpy.any()返回True比较is True失败但是== True有效.有谁知道为什么?

一个最小的例子

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')
Run Code Online (Sandbox Code Playgroud)

这段代码的输出就是== works.

Chr*_*nds 6

numpy拥有它自己的布尔值,numpy.True_并且numpy.False_与Python的原生布尔值具有不同的身份.无论如何,你应该==用于这种公平比较

>>> a.any() is True
False
>>> a.any() is numpy.True_
True
>>> True is numpy.True_
False
>>> True == numpy.True_
True
Run Code Online (Sandbox Code Playgroud)

  • 实际上,根本不检查布尔相等性.只做`if a.any()`或`if not a.any()`. (3认同)