【发布时间】:2019-11-10 14:21:18
【问题描述】:
此代码的目标是计算给定列表中出现次数最多的单词。我计划通过遍历字典来做到这一点。如果一个单词出现的次数比存储在变量 rep_num 中的值多,它就会被重新分配。目前,变量 rep_num 保持为 0,并且不会重新分配给单词在列表中出现的次数。我相信这与尝试在 for 循环中重新分配它有关,但我不确定如何解决此问题。
def rep_words(novel_list):
rep_num=0
for i in range(len(novel_list)):
if novel_list.count(i)>rep_num:
rep_num=novel_list.count(i)
return rep_num
novel_list =['this','is','the','story','in','which','the','hero','was','guilty']
在给定的代码中,应该返回 2,但返回的是 0。
【问题讨论】:
-
你
count是一个整数 (i),它根本不会出现在你的列表中。
标签: python for-loop variables assign