我正在编写一个函数,该函数返回单词列表中出现次数最多的单词的出现次数。
def max_frequency(words):
"""Returns the number of times appeared of the word that
appeared the most in a list of words."""
words_set = set(words)
words_list = words
word_dict = {}
for i in words_set:
count = []
for j in words_list:
if i == j:
count.append(1)
word_dict[i] = len(count)
result_num = 0
for _, value in word_dict.items():
if value > result_num:
result_num = value
return result_num
例如:
words = ["Happy", "Happy", "Happy", "Duck", "Duck"]
answer = max_frequency(words)
print(answer)
3
但是这个函数在处理列表中的大量单词时速度很慢,例如,250,000 个单词的列表需要 4 分钟以上才能呈现输出。所以我正在寻求帮助来调整这个。
我不想进口任何东西。