类型错误:列表索引必须是整数,而不是str的

问题描述:

使用的变量的声明如下:类型错误:列表索引必须是整数,而不是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

你的问题可能是:

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

它是什么样子让我看到你正在长度为1的列表:

[label] 

然后你想通过索引从它那里得到一个元素:

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

但外括号内的东西,计算结果为一个字符串。并且字符串不能用于索引列表。

最终,这几乎可以肯定是而不是你正在尝试做什么,但我认为它解释了错误。一般来说,我会建议你避免使用这种长时间混淆的1-liners,并使用临时(但恰当命名)的变量将其分解为它的组成部分。这将使您的代码更易于理解,因此编写和开发起来会更容易。

+0

你能告诉我如何从字典中获取值吗?如果这不可能? – Soham

+0

@Soham - 当然这是可能的,但我没有很好的方式知道你想要获取哪个*值。尝试遵循我的建议,并希望你能够解开你的数据结构。 – mgilson