【发布时间】:2014-11-03 10:18:45
【问题描述】:
我的目标是拥有一个列表列表,其中外部列表中的每个项目在它的第一个索引中包含一个单词,以及它在第二个索引中遇到它的次数。例如,它应该如下所示:
[["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] 列表不为空”
Crash with list index out of range error 指向行if innerList[0] == word
【问题讨论】:
-
为什么不使用
Counter?这正是它的用途。 -
您的
else: print "List empty."语句在循环内。您的意思是要在那儿调用那条线吗?
标签: python arrays list indexing