Python 数据类型列表中的字段名?

Python 数据类型列表中的字段名?,python,matlab,numpy,scipy,Python,Matlab,Numpy,Scipy,我正在使用中的代码将matlab结构读入Python。我想列出出现在数据类型列表中的字段的名称。我的代码是: matfile =loadmat(dataDirStr + matFileName, struct_as_record=True) # a dictionary theseKeys = matfile.keys() #as list thisDict = matfile[ theseKeys[ 1 ] ] #type = void1152, size = (1

我正在使用中的代码将matlab结构读入Python。我想列出出现在数据类型列表中的字段的名称。我的代码是:

matfile   =loadmat(dataDirStr + matFileName, struct_as_record=True) # a dictionary
theseKeys = matfile.keys()            #as list
thisDict  = matfile[ theseKeys[ 1 ] ] #type = void1152, size = (1, 118)
#
#screen display of contents is:
#
dtype    = [ ( 'Aircraft_Name', 'O'), ('Low_Mass', 'O') ]
因此,考虑到这一点,我想创建一个dtype中条目的列表:

thisList = [ 'Aircraft_Name', 'Low_Mass' ] #etc., etc.
这样就保留了数据类型条目中的名称顺序


您能帮助我吗?

在每次迭代中,只需使用列表理解并从每个元组中提取第一项:

thisList = [item[0] for item in dtype]
或作为一种功能性方法,使用:

此元组便于逐个设置或获取所有字段:

In [171]: x=np.empty((3,),dtype=dt)
In [172]: x
Out[172]: 
array([(None, None), (None, None), (None, None)], 
      dtype=[('Aircraft_Name', 'O'), ('Low_Mass', 'O')])
In [173]: for name in x.dtype.names:
     ...:     x[name][:]=['one','two','three']
     ...:     
In [174]: x
Out[174]: 
array([('one', 'one'), ('two', 'two'), ('three', 'three')], 
      dtype=[('Aircraft_Name', 'O'), ('Low_Mass', 'O')])
descr
是变量数据类型的列表描述;也可以从中提取名称:

In [180]: x.dtype.descr
Out[180]: [('Aircraft_Name', '|O'), ('Low_Mass', '|O')]
In [181]: [i[0] for i in x.dtype.descr]
Out[181]: ['Aircraft_Name', 'Low_Mass']
In [182]: x.dtype.names
Out[182]: ('Aircraft_Name', 'Low_Mass')

很公平的建议,但是如何从dict变量中的位置访问“dtype”?如果有帮助的话,我可以发送屏幕截图。([u'B788],[99817],[140000],[160000],[43000],[dtype=[('Aircraft_Name','O'),('Low_Mass','O'),(谢谢。但是,如上所述,dt变量嵌入在dict变量中,这正是我想要检索的。您已经给了我创建它的信息,这很好。但是,从dict变量中的数据类型动态创建列表怎么样?谢谢。如果
thisDict
是变量,一个数组,那么
isDict.dtype
是它的
dtype
,而
thisDict.dtype.names
是字段名。宾果。非常感谢。
In [171]: x=np.empty((3,),dtype=dt)
In [172]: x
Out[172]: 
array([(None, None), (None, None), (None, None)], 
      dtype=[('Aircraft_Name', 'O'), ('Low_Mass', 'O')])
In [173]: for name in x.dtype.names:
     ...:     x[name][:]=['one','two','three']
     ...:     
In [174]: x
Out[174]: 
array([('one', 'one'), ('two', 'two'), ('three', 'three')], 
      dtype=[('Aircraft_Name', 'O'), ('Low_Mass', 'O')])
In [180]: x.dtype.descr
Out[180]: [('Aircraft_Name', '|O'), ('Low_Mass', '|O')]
In [181]: [i[0] for i in x.dtype.descr]
Out[181]: ['Aircraft_Name', 'Low_Mass']
In [182]: x.dtype.names
Out[182]: ('Aircraft_Name', 'Low_Mass')