2012-11-21 70 views
-6

使用的變量的聲明如下:類型錯誤:列表索引必須是整數,而不是str的

self.features = {}  #dictionary defined for storing the features and the values 
self.featureNameList = [] #list to store the names and values of the features 
self.featureCounts = collections.defaultdict(lambda: 1) #the counts of the features and labels 
self.featureVectors = [] # 
self.labelCounts = collections.defaultdict(lambda: 0)    
def Classify(self):  #featureVector is a simple list like the ones that we use to train 
    probabilityPerLabel = {} 
    for label in self.labelCounts.keys(): 
     Prob = 0 
     for featureValue in self.featureVectors: 
      #print self.labelCounts[label] 
      Prob+=self.featureCounts[[label][self.featureNameList[self.featureVectors.index(featureValue)]][featureValue]]/self.labelCounts[label] 
      # Prob+= self.featureCounts(label, self.featureNameList[self.featureVectors.index(featureValue)], featureValue)/self.labelCounts[label] 
     probabilityPerLabel[label] = (self.labelCounts[label]/sum(self.labelCounts.values())) * (Prob) 
    print probabilityPerLabel 
    return max(probabilityPerLabel, key = lambda classLabel: probabilityPerLabel[classLabel]) 

的錯誤是在生產線生產:

Prob+=self.featureCounts[[label][self.featureNameList[self.featureVectors.index(featureValue)]][featureValue]]/self.labelCounts[label] 
+0

哪條線產生錯誤? – mgilson

+0

Prob + = self.featureCounts [[label] [self.featureNameList [self.featureVectors.index(featureValue)]] [featureValue]]/self.labelCounts [標籤] – Soham

回答

2

你的問題可能是:

[label][self.featureNameList[self.featureVectors.index(featureValue)] 

它是什麼樣子讓我看到你正在長度爲1的列表:

[label] 

然後你想通過索引從它那裏得到一個元素:

[self.featureNameList[self.featureVectors.index(featureValue)] 

但外括號內的東西,計算結果爲一個字符串。並且字符串不能用於索引列表。

最終,這幾乎可以肯定是而不是你正在嘗試做什麼,但我認爲它解釋了錯誤。一般來說,我會建議你避免使用這種長時間混淆的1-liners,並使用臨時(但恰當命名)的變量將其分解爲它的組成部分。這將使您的代碼更易於理解,因此編寫和開發起來會更容易。

+0

你能告訴我如何從字典中獲取值嗎?如果這不可能? – Soham

+0

@Soham - 當然這是可能的,但我沒有很好的方式知道你想要獲取哪個*值。嘗試遵循我的建議,並希望你能夠解開你的數據結構。 – mgilson

相關問題