每日一题 【每日一题】单词出现频率统计-Python-20211028

Jack · 2021年10月29日 · 最后由 Jack 回复于 2021年10月29日 · 47 次阅读
本帖已被设为精华帖!

给定一个单词列表,求出这个列表中出现频次最高的 n 个单词

Jack 将本帖设为了精华贴 10月29日 06:51

参考代码:

class Solution:
    def topKFrequentWords(self, words, k):
        dict = {}
        res = []
        for word in words:
            if word not in dict:
                dict[word] = 1
            else:
                dict[word] += 1
        sorted_d = sorted(dict.items(), key = lambda x:x[1], reverse=True)
        for i in range(k):
            res.append(sorted_d[i][0])
        return res 
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册