第一个比较没有意义,第二个比较is有意义的。
With numpy.int16 > numpy.float32
我们正在比较两个type
对象:
>>> type(numpy.int16)
type
>>> numpy.int16 > numpy.float32 # I'm using Python 3
TypeError: unorderable types: type() > type()
在 Python 3 中,这种比较会立即失败,因为没有定义顺序type
实例。在 Python 2 中,返回一个布尔值,但不能依赖于一致性(它会回退到比较内存地址或其他实现级别的东西)。
第二次比较does在 Python 3 中工作,并且它一致地工作(与 Python 2 相同)。这是因为我们现在正在比较dtype
实例:
>>> type(numpy.dtype('int16'))
numpy.dtype
>>> numpy.dtype('int16') > numpy.dtype('float32')
False
>>> numpy.dtype('int32') < numpy.dtype('|S10')
False
>>> numpy.dtype('int32') < numpy.dtype('|S11')
True
这个排序背后的逻辑是什么?
dtype
实例根据一个实例是否可以(安全)转换为另一个实例进行排序。一种类型是少于如果可以的话另一个安全施放到那种类型。
对于比较运算符的实现,请参见描述符.c https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/descriptor.c;特别是在arraydescr_richcompare https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/descriptor.c#l3451功能。
这是什么<
运算符映射到:
switch (cmp_op) {
case Py_LT:
if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(self, new)) {
result = Py_True;
}
else {
result = Py_False;
}
break;
本质上,NumPy 只是检查这两种类型是否 (i) 不等价,以及 (ii) 第一种类型可以转换为第二种类型。
此功能也在 NumPy API 中公开为np.can_cast http://docs.scipy.org/doc/numpy/reference/generated/numpy.can_cast.html:
>>> np.can_cast('int32', '|S10')
False
>>> np.can_cast('int32', '|S11')
True