Python np.uint16是';与np.uint16不同
我正在尝试使用字典查找将numpy数据类型映射到关联的值。我观察到以下违反直觉的行为:Python np.uint16是';与np.uint16不同,python,numpy,Python,Numpy,我正在尝试使用字典查找将numpy数据类型映射到关联的值。我观察到以下违反直觉的行为: dtype = np.uint16 x = np.array([0, 1, 2], dtype=dtype) assert x.dtype == dtype d = {np.uint8: 8, np.uint16: 16, np.uint32: 32, np.float32: 32} print(dtype in d) # prints True print(x.dtype in d) # prints
dtype = np.uint16
x = np.array([0, 1, 2], dtype=dtype)
assert x.dtype == dtype
d = {np.uint8: 8, np.uint16: 16, np.uint32: 32, np.float32: 32}
print(dtype in d) # prints True
print(x.dtype in d) # prints False
使用其他数据类型会产生类似的结果
因此我们得到了
np.uint16==x.dtype
,但是前者可以在字典的键中找到,而后者则不能。任何解释和/或简单的解决方法都将不胜感激。x.dtype
返回一个dtype
对象(请参阅)
要获取内部的类型,需要调用x.dtype.type
:
print(x.dtype.type in d) # True
这是预期的行为:
dtype = np.uint16
x = np.array([0, 1, 2], dtype=dtype)
assert x.dtype == dtype
d = {np.uint8: 8, np.uint16: 16, np.uint32: 32, np.float32: 32}
print(dtype in d) # prints True
print(x.dtype in d) # prints False
np.uint16
是未初始化的,因此dtype
实际上是一个类,而x.dtype
实际上是一个数据类型对象()
另一个答案显示了一种解决方法。数据类型的工作方式与乍一看不一样
np.uint16
不是一个数据类型对象。它可以换成一辆np.uint16
是一个类型对象,表示uint16数据类型的类型
x.dtype
是一个实际值,而dtype对象以一种奇怪的方式实现=
,这种方式是不可传递的,并且与哈希
不一致dtype==other
基本上实现为dtype==np.dtype(other)
当other
还不是一个数据类型时。您可以在中看到详细信息
特别是,
x.dtype
比较等于np.uint16
,但是它没有相同的散列,因此dict查找没有找到它。您知道为什么会存在这种行为吗?从Python文档开始:“唯一需要的属性是比较相等的对象具有相同的哈希值;”。所以Numpy决定违反这个要求,但为什么呢?@a_guest:我不知道,但现在改变行为为时已晚。请注意,数据类型不能通过其.type
唯一标识。例如,所有结构化数据类型都有dtype.type为numpy.void
。