Python 从字符串创建numpy.dtype而不使用不一致性

Python 从字符串创建numpy.dtype而不使用不一致性,python,numpy,numpy-dtype,Python,Numpy,Numpy Dtype,numpy是否有从字符串创建数据类型的方法numpy.dtype()几乎就是我所需要的,但它会造成不一致: import numpy as np dtype1 = np.dtype('float32') dtype2 = np.float32 # This works (prints "same") if dtype1 == dtype2: print("same") # I want the code in the line below t

numpy
是否有从字符串创建数据类型的方法
numpy.dtype()
几乎就是我所需要的,但它会造成不一致:

import numpy as np

dtype1 = np.dtype('float32')
dtype2 = np.float32

# This works (prints "same")
if dtype1 == dtype2:
    print("same")

# I want the code in the line below to produce a set with one item
# However, the resulting set is: {dtype('float32'), <class 'numpy.float32'>}
dtypes = {dtype1, dtype2}

# One way to fix the above is to write the following, but this is ugly
dtypes = {np.empty(1, dtype1).dtype, np.empty(1, dtype2).dtype}
将numpy导入为np
dtype1=np.dtype('float32')
dtype2=np.32
#这是有效的(打印“相同”)
如果dtype1==dtype2:
打印(“相同”)
#我希望下面一行中的代码生成一个包含一个项目的集合
#但是,结果集是:{dtype('float32'),}
dtypes={dtype1,dtype2}
#解决上述问题的一种方法是编写以下内容,但这很难看
dtypes={np.empty(1,dtype1).dtype,np.empty(1,dtype2).dtype}
有没有一种优雅的方法可以解决上述问题


谢谢

当您的两个对象用作
dtype
参数时,它们做的是相同的事情,但它们不是相同的事情,甚至不是相同类型的事情:

In [51]: np.dtype('float32')                                                                         
Out[51]: dtype('float32')
In [52]: np.float32                                                                                  
Out[52]: numpy.float32
In [53]: type(np.dtype('float32'))                                                                   
Out[53]: numpy.dtype
In [54]: type(np.float32)                                                                            
Out[54]: type
一个是
np.dtype
的实例,另一个是函数

np.empty(1,'f')。dtype
是另一个生成所需数据类型的字符串,但在
集合中显然不匹配

使用该功能:

In [59]: np.float32(1).dtype                                                                         
Out[59]: dtype('float32')