Python TypeError:列表索引必须是整数,而不是str
所用变量的声明如下:Python TypeError:列表索引必须是整数,而不是str,python,python-2.7,Python,Python 2.7,所用变量的声明如下: 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 f
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]
你的问题可能是:
[label][self.featureNameList[self.featureVectors.index(featureValue)]
在我看来,您正在制作一个长度为1的列表:
[label]
然后您试图通过索引从中获取元素:
[self.featureNameList[self.featureVectors.index(featureValue)]
但外括号内的内容计算为字符串。和字符串不能用于索引列表
最终,这几乎肯定不是你想要做的,但我认为这解释了错误。总的来说,我建议您避免像这样冗长而混乱的1行程序,并使用临时但恰当命名的变量将其分解为各个组成部分。这将使您的代码更易于理解,从而更易于编写和开发。哪一行产生错误?Prob+=self.featureCounts[[label][self.featureNameList[self.featureVectors.indexfeatureValue]][featureValue]/self.labelCounts[label]您能告诉我如何从字典中获取值吗?如果这不可能的话?@Soham-当然可能,但我没有办法知道你想得到什么价值。试着按照我的建议去做,希望你能解开你的数据结构。