2016-05-09 68 views
0

我是新來的python,我試圖在(10 x 3)矩陣中存儲具有最高相關性的10個項目,爲此我只想簡單地檢查最後一行值(這是最小值),如果插入值更高的值,則重新排序行。我的問題是,我不知道如何訪問位置(i,j)中的特定項目,以便讀取和修改其值。這是我的代碼:在結構化數組中存儲十個最相關的項目Python

dtype = [('tag1', 'S8'), ('tag2', 'S8'), ('correlation', 'f8')] 
most_related_tags = np.zeros((10,3),dtype=dtype) 

for i in tags: 
    for j in tags: 
    if(i['tag'] != j['tag']): 
     correlation = tagCorrelation(tagsFile,str(i['tag']),str(j['tag'])) 

     if(correlation > 0): 
      print most_related_tags[9,2] 
      if(most_related_tags[9,2] < correlation): 
       print "entered" 
       most_related_tags[9,2] = correlation; 
       most_related_tags[9,0] = str(i['tag']); 
       most_related_tags[9,1] = str(j['tag']); 
       most_related_tags = np.sort(most_related_tags,order='correlation') 

的問題是,我的程序不會進入if語句,因爲most_related_tags [9,2]既不most_related_tags.item(9,2)返回正確的對象

回答

1

有你看看你在開始時創建的數組?這是一個10x3陣列,其中每個元素是一個結構化的記錄 - 有3個值

In [173]: most_related_tags 
Out[173]: 
array([[(b'', b'', 0.0), (b'', b'', 0.0), (b'', b'', 0.0)], 
     [(b'', b'', 0.0), (b'', b'', 0.0), (b'', b'', 0.0)], 
     [(b'', b'', 0.0), (b'', b'', 0.0), (b'', b'', 0.0)], 
     ... 
     [(b'', b'', 0.0), (b'', b'', 0.0), (b'', b'', 0.0)], 
     [(b'', b'', 0.0), (b'', b'', 0.0), (b'', b'', 0.0)]], 
     dtype=[('tag1', 'S8'), ('tag2', 'S8'), ('correlation', '<f8')]) 

所以,你必須訪問各個標籤與most_related_tags[9,1]['tag1']或類似的東西。

我懷疑你真正想要的10個項目的數組,

In [174]: tags = np.zeros((10,),dtype=dtype) 

In [175]: tags 
Out[175]: 
array([(b'', b'', 0.0), (b'', b'', 0.0), (b'', b'', 0.0), (b'', b'', 0.0), 
     (b'', b'', 0.0), (b'', b'', 0.0), (b'', b'', 0.0), (b'', b'', 0.0), 
     (b'', b'', 0.0), (b'', b'', 0.0)], 
     dtype=[('tag1', 'S8'), ('tag2', 'S8'), ('correlation', '<f8')]) 

,您訪問與tags[9]['tag1'],或tags[3]記錄,或tags['correlaton']所有相關個別變量的值。

那麼你應該能夠與設定值:

 if(most_related_tags[9]['correlation'] < correlation): 
      most_related_tags[9]['correlation'] = correlation 
      most_related_tags[9]['tag1'] = str(i['tag']) 
      most_related_tags[9]['tag2'] = str(j['tag']) 

或元組

most_related_tags[9] = (str(i['tag']), str(ij['tag']), correlation) 

您可以通過設置一個結構數組的值設置的全程記錄:

by indexing element by record number and field name 
by setting all values of a field with an array or list 
by setting a record with a tuple of values 
by setting multiple records with a list of tuples. 
+0

是的,我想要一個包含三個字段的數組。萬分感謝 –