Python“;列表索引超出范围“;错误
我的目标是建立一个列表列表,其中外部列表中的每个项目在其第一个索引中包含一个单词,以及在第二个索引中遇到它的次数。例如,它应该如下所示:Python“;列表索引超出范围“;错误,python,arrays,list,indexing,Python,Arrays,List,Indexing,我的目标是建立一个列表列表,其中外部列表中的每个项目在其第一个索引中包含一个单词,以及在第二个索引中遇到它的次数。例如,它应该如下所示: [["test1",0],["test2",4],["test3",8]] 唯一的问题是,例如,当我试图从第一个内部列表中访问单词“test1”时,我会得到一个索引超出范围的错误。以下是我尝试执行此操作的代码: stemmedList = [[]] f = open(a_document_name, 'r') #read each line of fil
[["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
最终的输出结果是:
列表为空。
[“测试1”,0]
“列表不为空”
如果innerList[0]==word假设
词干列表
和未词干列表
相似,则列表索引超出范围错误导致崩溃,该错误指向行
stemmedList = [[]]
您的列表列表中有一个空列表,它没有[0]
。只需将其初始化为:
stemmedList = []
您有a=[[]]
现在,当您在遇到第一个单词后添加到此列表时
a=[[],['test',0]]
在下一次迭代中,您将访问不存在的空列表的第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}
为什么不使用计数器
?这正是它的用途。您的否则:打印“List empty”。
语句在循环中。您的意思是在那里调用该行吗?