[英]List Index Error on Python
Im writing a program to try to calculate how many times the most repeated word in a list occurs. 我正在编写一个程序来尝试计算列表中最重复的单词出现了多少次。 I keep getting an error that says: index error. 我不断收到一条错误消息:索引错误。 Even though when I print the list of my word_list, it shows there are 108 elements. 即使我打印word_list的列表时,它也显示有108个元素。 Could someone point me in the right direction as to where my error is? 有人能指出我错误的正确方向吗?
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
List indexing goes from 0
to length-1
. 列表索引从0
到length-1
。
In your while loop, you've told the num
to go from 0
to length
. 在while循环中,您告诉num
从0
到length
。 That's why you have an index error. 这就是为什么您有一个索引错误。
Simply change num <= length
to num < length
. 只需将num <= length
更改为num < length
。 That should fix your code for you. 那应该为您修复代码。
As an aside, there are much better ways to do this particular task. 顺便说一句,有更好的方法来完成此特定任务。 A simple two liner: 一个简单的两个班轮:
from collections import Counter
print(Counter(word_list).most_common(1))
Counter
will calculate the frequencies of each element in your list for you, and most_common(1)
will return the element with the highest frequency in your list. Counter
将为您计算列表中每个元素的频率, most_common(1)
将返回列表中频率最高的元素。
Just to mention that there is a more compact solution to your problem: 只需提一下,您的问题有一个更紧凑的解决方案:
word_list =['this' ,'is', 'a', 'test', 'is']
for word in set(word_list):
print word, ": ", word_list.count(word)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.