Python上的列表索引错误

2024-06-16 16:15:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序来计算列表中重复次数最多的单词出现的次数。我不断得到一个错误,上面写着:索引错误。尽管当我打印单词列表时,它显示有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

Tags: 程序元素列表if错误单词次数length
2条回答

列表索引从0length-1。你知道吗

在while循环中,您已经告诉num0转到length。这就是为什么你有一个索引错误。你知道吗

只需将num <= length更改为num < length。那应该能帮你修复代码。你知道吗


另外,还有更好的方法来完成这项任务。简单的两行:

from collections import Counter

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

Counter将为您计算列表中每个元素的频率,most_common(1)将返回列表中频率最高的元素。你知道吗

我只想说,有一个更紧凑的解决方案,你的问题:

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

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

相关问题 更多 >