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

Python中如何计算值为列表的字典内各单词的出现概率

你编写的代码直接将列表v除以列表长度,类型不匹配才会触发TypeError,确实需要先统计列表中每个唯一元素的出现频次后再计算概率。

可以使用Python标准库的collections.Counter快速完成频次统计,完整实现代码如下:

from collections import Counter

my_dict = {'Summer':['Summer','Summer','gone'],'gone':['forever'],'forever':['gone']}
prob_dict = {}

for key, word_list in my_dict.items():
    total_cnt = len(word_list)
    # 统计每个单词的出现次数
    word_counter = Counter(word_list)
    # 计算概率,保留两位小数
    prob_dict[key] = {word: round(count / total_cnt, 2) for word, count in word_counter.items()}

print(prob_dict)

运行后输出结果为:

{'Summer': {'Summer': 0.67, 'gone': 0.33}, 'gone': {'forever': 1.0}, 'forever': {'gone': 1.0}}

如果你需要严格得到0.66而非四舍五入的0.67,可以调整概率计算的截断逻辑,将字典推导式修改为:

prob_dict[key] = {word: int(count / total_cnt * 100) / 100 for word, count in word_counter.items()}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 10:24:03