2016-11-28 70 views
1

我有一個類abalone與三個屬性M,IF。像這樣訪問他們:對類屬性的迭代

abalone.M 
Out[81]: 
array([[ 0.455 , 0.365 , 0.095 , ..., 0.2245, 0.101 , 0.15 ], 
     [ 0.35 , 0.265 , 0.09 , ..., 0.0995, 0.0485, 0.07 ], 
     [ 0.44 , 0.365 , 0.125 , ..., 0.2155, 0.114 , 0.155 ], 
     ..., 
     [ 0.59 , 0.44 , 0.135 , ..., 0.439 , 0.2145, 0.2605], 
     [ 0.6 , 0.475 , 0.205 , ..., 0.5255, 0.2875, 0.308 ], 
     [ 0.71 , 0.555 , 0.195 , ..., 0.9455, 0.3765, 0.495 ]]) 

工作出色。我將如何去迭代他們?我的嘗試

for item in [M, I, F]: 
    abalone.item 
    --------------------------------------------------------------------------- 
NameError         Traceback (most recent call last) 
<ipython-input-84-c9c2187c3451> in <module>() 
----> 1 for item in [M, I, F]: 
     2  abalone.item 

NameError: name 'M' is not defined 

不幸運。

編輯:試圖

for item in ['M', 'I', 'F']: 
    abalone.item 
--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 
<ipython-input-86-b9d61335686f> in <module>() 
     1 for item in ['M', 'I', 'F']: 
----> 2  abalone.item 

AttributeError: 'Abalone' object has no attribute 'item' 

也不起作用。

+0

abalone.M的類型是'array.array'還是'list'?抱歉讓我困惑。 –

+1

這是一個numpy數組。 – sbm

回答

1

試試這個:

for attr, value in abalone.__dict__.items(): 
    print attr,value 

如果不工作,然後讓我知道。

編輯(根據在問題發生變動):

l = ['M','I','F'] 
for attr, value in x.__dict__.iteritems(): 
    if attr in l: 
     print attr,value 

這裏L將包含您要訪問的屬性的子集。

+0

對不起,這是一個錯字。更正了我的問題,並嘗試了您的建議,但不幸的是無法正常工作。 – sbm

+0

沒關係。我編輯我的答案嘗試這種方法。測試這個自己所以它應該工作。 –

+0

謝謝,這工作,但不幸的是,它並沒有幫助我的情況,因爲我只是遍歷子集。所以我特別需要讓我的代碼在上面工作.. – sbm