You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python按词频排序字典单词:sorted()使用疑问及实现求助

按词频降序排序单词的实现方法

假设你已经通过make_dict函数得到了词频字典,要实现按词频从高到低排序并输出指定格式的结果,直接用sorted()就能搞定,关键是给它指定排序依据的key参数。

完整实现代码

def make_dict(s):
    # 这里是你已实现的词频统计逻辑,示例如下:
    word_list = s.split()
    count_dict = {}
    for word in word_list:
        count_dict[word] = count_dict.get(word, 0) + 1
    return count_dict

# 获取词频字典
counts = make_dict("test is test tests tests tests")

# 按词频降序排序单词
sorted_words = sorted(counts.keys(), key=lambda word: counts[word], reverse=True)

# 转换为要求的字符串格式
result = " ,".join(sorted_words)

print(result)  # 输出:tests ,test ,is

关键部分说明

  • sorted(counts.keys(), key=lambda word: counts[word], reverse=True):
    • counts.keys()是待排序的单词集合
    • key=lambda word: counts[word]指定排序依据为单词对应的词频值
    • reverse=True设置为降序排列(默认是升序)
  • " ,".join(sorted_words):将排序后的单词列表用" ,"连接成目标格式的字符串

内容的提问来源于stack exchange,提问作者Honza Alt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 01:06:19