我正在尝试使用字典查找将 numpy dtypes 映射到关联的值。我观察到以下违反直觉的行为:
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
Run Code Online (Sandbox Code Playgroud)
使用其他 dtypes 会产生类似的结果。
所以我们有那个np.uint16 == x.dtype,但前者在字典的键中找到,而后者则没有。任何解释和/或简单的解决方法将不胜感激。
Dtypes 不像乍一看那样工作。np.uint16 不是dtype 对象。它只是可以转换为一个。np.uint16是一个类型对象,表示uint16 dtype的数组标量的类型。
x.dtype是一个实际的dtype object,并且 dtype 对象==以一种奇怪的方式实现,它是非传递性的并且与hash. dtype == other基本上实现为dtype == np.dtype(other)whenother还不是 dtype。您可以在源中查看详细信息。
特别是,x.dtype比较等于np.uint16,但它没有相同的哈希值,因此 dict 查找找不到它。
| 归档时间: |
|
| 查看次数: |
1104 次 |
| 最近记录: |