列出Python上的索引错误

时间:2016-04-10 05:48:08

标签: python list function loops indexing

我正在编写一个程序,试图计算列表中重复次数最多的单词出现次数。我一直收到错误消息:索引错误。即使我打印word_list列表,它显示有108个元素。有人能指出我的错误在哪里吗?

  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

1 个答案:

答案 0 :(得分:1)

请注意,您的问题有一个更紧凑的解决方案:

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

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