python 问题:将 `is` 关系运算符与 `numpy.all()` 一起使用

python issue: using `is` relational operator with `numpy.all()`

当使用 is 运算符比较 True 值的布尔数组的 numpy.all() 时,我得到一个意外的 False 作为输出。但是,在使用 == 运算符时,我得到了预期的结果 (True)。此比较失败的可能原因是什么?

下面附上示例代码。

In[2]: import sys
In[3]: print(sys.version)
3.9.5 

In[4]: import numpy as np
In[5]: np.__version__
'1.20.3'

In[6]: bool1 = True
In[7]: bool1 is True
True

In[8]: bool1 == True
True

In[9]: bool_arr = np.array([True, True, True, True])
In[10]: bool_arr.all()
True

In[11]: bool_arr.all() == True
True

In[12]: bool_arr.all() is True
False

从上面的代码可以看出,在输入12中,预期结果是True,但实际结果是False

我在 Ubuntu 中使用 pyenv 作为 python 的环境。

编辑: 如评论中所建议,这不是使用 python 的最佳做法。但是,我很想知道这次失败的根本原因。

如果您检查 bool_arr.all() 的类型,答案将立即显而易见:

>>> bool_arr.all()
<class 'numpy.bool_'>

np.all returns numpy bool_ 的一个实例,与 python 的内置 bool 不同 class ] 类型。不同类型的实例不能是同一个对象,这就是is告诉你的。

检查真实性的正确方法是让 python 为您将表达式包装在 bool 中,例如,在 if 语句中,如 if bool_arr.all():.