【问题标题】:Field names from dtype listing?dtype列表中的字段名称?
【发布时间】:2016-12-13 13:31:01
【问题描述】:

我正在使用来自 scipy.io.loadmat nested structures (i.e. dictionaries) 的代码将 matlab 结构读入 Python。我想列出出现在 dtype 列表中的字段名称列表。我的代码是:

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.

这样可以保留 dtype 条目中名称的顺序。

你能帮帮我吗?

【问题讨论】:

    标签: python matlab numpy scipy


    【解决方案1】:

    只需使用列表推导式并在每次迭代中从每个元组中提取第一项:

    thisList = [item[0] for item in dtype]
    

    或者作为一种功能方法使用zip()

    thisList = next(zip(*dtype)) # in python 2.x zip(*dtype)[0]
    

    【讨论】:

    • 足够公平的建议,但是如何从 dict 变量中的位置访问“dtype”?如果有帮助,我可以发送屏幕截图。
    • ([u'B788__'], [[99817]], [[140000]], [[160000]], [[43000]], dtype=[('Aircraft_Name', 'O '), ('Low_Mass', 'O'), (
    【解决方案2】:
    In [168]: dt=np.dtype([ ( 'Aircraft_Name', 'O'), ('Low_Mass', 'O') ])
    In [169]: dt
    Out[169]: dtype([('Aircraft_Name', 'O'), ('Low_Mass', 'O')])
    In [170]: dt.names
    Out[170]: ('Aircraft_Name', 'Low_Mass')
    

    这个元组便于一一设置或获取所有字段:

    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是变量dtype的列表描述;名称也可以从中提取:

    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')
    

    【讨论】:

    • 谢谢。但是,如上所述,dt 变量嵌入在 dict 变量中,这就是我要检索的内容。你已经给了我创建它的信息,这很好。但是,如何从 dict 变量中的 dtype 动态创建列表?谢谢。
    • 如果thisDict是变量,一个数组,那么thisDict.dtype是它的dtypethisDict.dtype.names是字段名。
    • 宾果游戏。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多