2016-08-07 6 views
0

나는 scipy.io.loadmat nested structures (i.e. dictionaries)에서 코드를 사용하여 Python으로 matlab 구조체를 읽습니다. dtype 목록에 나타나는 필드의 이름 목록을 만들고 싶습니다. 내 코드는 다음과 같습니다dtype 목록의 필드 이름은 무엇입니까?

thisList = [ 'Aircraft_Name', 'Low_Mass' ] #etc., etc. 

이 같은 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에있는 항목의 목록을 만들고 싶습니다 .

도와주세요.

답변

1

그냥 지능형리스트를 사용하고, 각 튜플에서 첫 번째 항목을 데리러 각각의 반복 :

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

충분한 제안이 있지만, dict 변수 내의 위치에서 'dtype'에 액세스하려면 어떻게해야합니까? 도움이된다면 스크린 샷을 보낼 수 있습니다. –

+0

데이터가 화면에 표시됩니다 (죄송합니다). –

+0

([u'B788__ '], [99817], [[140000]], [[160000]], [[43000]], dtype = 그러나, dt 변수는 위에서 언급 한 것처럼 dict 변수에 내장되어 있으며, 검색하고자하는 내용입니다. ('(Aircraft_Name', 'O'), ('Low_Mass', 'O'), –

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

이 튜플 :

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

또는 기능적 접근 방식을 사용 zip()

모든 필드를 하나씩 설정하거나 가져 오는 데 편리합니다.

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

. dict 변수 내에서 dtype으로부터 동적으로리스트를 생성하는 것은 어떻습니까? 감사합니다. –

+0

'thisDict'가 변수라면, 배열은'thisDict입니다. dtype'은'dtype'이고,'thisDict.dtype.names'는 필드 이름입니다. – hpaulj

+0

빙고. 정말 고마워요. –

관련 문제