Python上的列表索引错误
我正在写一个程序来计算列表中重复次数最多的单词出现的次数。我一直收到一个错误,上面写着:索引错误。尽管当我打印单词列表时,它显示有108个元素。有人能给我指出错误所在的正确方向吗Python上的列表索引错误,python,list,function,loops,indexing,Python,List,Function,Loops,Indexing,我正在写一个程序来计算列表中重复次数最多的单词出现的次数。我一直收到一个错误,上面写着:索引错误。尽管当我打印单词列表时,它显示有108个元素。有人能给我指出错误所在的正确方向吗 length = len(word_list) num = 0 print(length) while num <= length: ele = word_list[num] if ele in wordDict:
length = len(word_list)
num = 0
print(length)
while num <= length:
ele = word_list[num]
if ele in wordDict:
wordDict[ele] = wordDict[ele] +1
repeat = repeat + 1
if repeat > highestRepeat:
highestRepeat = repeat
else:
wordDict[ele] = 1
repeat = 1
num = num+1
length=len(单词列表)
num=0
打印(长度)
而num highestRepeat:
highestRepeat=重复
其他:
wordDict[ele]=1
重复=1
num=num+1
列表索引从0
到length-1
在while循环中,您已经告诉num
从0
转到length
。这就是索引错误的原因
只需将列表索引从
0
更改为length-1
在while循环中,您已经告诉num
从0
转到length
。这就是索引错误的原因
只需更改
num,就可以知道您的问题有一个更简洁的解决方案:
word_list =['this' ,'is', 'a', 'test', 'is']
for word in set(word_list):
print word, ": ", word_list.count(word)
只需提到,有一个更紧凑的解决方案可以解决您的问题:
word_list =['this' ,'is', 'a', 'test', 'is']
for word in set(word_list):
print word, ": ", word_list.count(word)
你在哪里定义重复?我认为您应该在中使用you justif wordDict[ele]>highestRepeat
,而num在哪里定义repeat?我认为你应该在中使用if wordDict[ele]>highestRepeat
,而num将打印所有单词及其计数,而不是最大计数的单词(如OP所要求的)。正确,计数器是更好的解决方案,答案是交叉的。只是想指出使用标准python方法避免循环的方向。这将打印所有单词及其计数,而不是最大计数的单词(如OP所要求的)。正确,计数器是一个更好的解决方案,答案是交叉的。只是想通过使用标准的python方法指出避免循环的方向。