2016-04-10 73 views
1

我正在编写一个程序来尝试计算列表中最重复的单词出现次数。我不断收到一个错误,说:索引错误。尽管当我打印word_list的列表时,它显示有108个元素。有人能指出我的方向是错误的吗?Python上的列表索引错误

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 
+0

你在哪里定义重复?我认为你应该使用你'if wordDict [ele]> highestRepeat' – kame

+1

在'while num <= length:'change'<='到'<' –

回答

3

列表索引去从0length-1

在你的while循环中,你告诉num0length。这就是为什么你有索引错误。

只需将num <= length更改为num < length即可。这应该为你解决你的代码。


顺便说一句,有很多更好的方法来做这个特定的任务。简单的两个班轮:

from collections import Counter 

print(Counter(word_list).most_common(1)) 

Counter将计算每个元素的频率,在列表中的你,和most_common(1)将与列表中的最高频率返回元素。

1

只是提一提,还有一个更紧凑的解决问题的方法:

word_list =['this' ,'is', 'a', 'test', 'is'] 

for word in set(word_list): 
    print word, ": ", word_list.count(word) 
+0

这将打印所有的单词和它们的计数,而不是最大的单词计数(如OP所要求的)。 –

+0

正确,Counter是更好的解决方案,答案已经越过。只是想通过使用标准的python方法来指出避免循环的方向。 – tfv