第一个比较没有意义,第二个是有意义的。
使用
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中,会返回布尔值,但不能保证一致性(它会回退到比较内存地址或其他实现级别的东西)。第二个比较在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
实例会被排序。如果一个类型可以被安全地转换为另一个类型,则该类型
小于另一个类型。
要查看比较运算符的实现,请参阅
descriptor.c;特别是
arraydescr_richcompare
函数。
下面是
<
运算符的映射:
switch (cmp_op) {
case Py_LT:
if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(self, new)) {
result = Py_True;
}
else {
result = Py_False;
}
break;
基本上,NumPy只检查这两种类型不相等,并且第一种类型可以转换为第二种类型。
此功能也在NumPy API中公开,称为
np.can_cast
:
>>> np.can_cast('int32', '|S10')
False
>>> np.can_cast('int32', '|S11')
True
np.find_common_type
,但我仍然对这里发生的事情感兴趣。谢谢! - farenorthnumpy
1.9.2,两个比较都返回“False”。正如下面的答案所述,在Python 3中这是毫无意义的,并已被删除。 - MattDMo