Python "列表索引超出范围"错误
我的目标是创建一个列表的列表,外层列表中的每个项目都包含一个单词,单词在第一个位置,第二个位置是它出现的次数。举个例子,它应该看起来像这样:
[["test1",0],["test2",4],["test3",8]]
唯一的问题是,当我尝试访问第一个内层列表中的单词“test1”时,我遇到了“索引超出范围”的错误。以下是我尝试实现这个功能的代码:
stemmedList = [[]]
f = open(a_document_name, 'r')
#read each line of file
fileLines = f.readlines()
for fileLine in fileLines:
#here we end up with stopList, a list of words
thisReview = Hw1.read_line(fileLine)['text']
tokenList = Hw1.tokenize(thisReview)
stopList = Hw1.stopword(tokenList)
#for each word in stoplist, compare to all terms in return list to
#see if it exists, if it does add one to its second parameter, else
#add it to the list as ["word", 0]
for word in stopList:
#if list not empty
if not len(unStemmedList) == 1: #for some reason I have to do this to see if list is empty, I'm assuming when it's empty it returns a length of 1 since I'm initializing it as a list of lists??
print "List not empty."
for innerList in unStemmedList:
if innerList[0] == word:
print "Adding 1 to [" + word + ", " + str(innerList[1]) + "]"
innerList[1] = (innerList[1] + 1)
else:
print "Adding [" + word + ", 0]"
unStemmedList.append([word, 0])
else:
print "List empty."
unStemmedList.append([word, 0])
print unStemmedList[len(unStemmedList)-1]
return stemmedList
最终的输出结果是:
列表是空的。
["test1",0]
列表不为空
程序崩溃,出现索引超出范围的错误,错误发生在这一行 if innerList[0] == word
3 个回答
0
这不是更简单吗?
counts = dict()
def plus1(key):
if key in counts:
counts[key] += 1
else:
counts[key] = 1
stoplist = "t1 t2 t1 t3 t1 t1 t2".split()
for word in stoplist:
plus1(word)
counts
{'t2': 2, 't3': 1, 't1': 4}
0
假设 stemmedList
和 unStemmedList
是相似的
stemmedList = [[]]
你在一个列表的列表中有一个空列表,它没有 [0]
。与其这样,不如直接初始化为:
stemmedList = []
0
你有一个变量 a = [[]]
,这表示你创建了一个包含一个空列表的列表。
现在,当你在遇到第一个单词后往这个列表里添加内容时,变成了
a = [ [], ['test', 0] ]
,也就是说,列表里现在有两个元素,第一个是空列表,第二个是一个包含“test”和0的列表。
在接下来的操作中,你试图访问空列表的第0个元素,但这个空列表里什么都没有,所以你会遇到问题。