我正在写一个程序来计算列表中重复次数最多的单词出现的次数。我不断得到一个错误,上面写着:索引错误。尽管当我打印单词列表时,它显示有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
列表索引从
0
到length-1
。你知道吗在while循环中,您已经告诉
num
从0
转到length
。这就是为什么你有一个索引错误。你知道吗只需将
num <= length
更改为num < length
。那应该能帮你修复代码。你知道吗另外,还有更好的方法来完成这项任务。简单的两行:
Counter
将为您计算列表中每个元素的频率,most_common(1)
将返回列表中频率最高的元素。你知道吗我只想说,有一个更紧凑的解决方案,你的问题:
相关问题 更多 >
编程相关推荐