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
相关产品推荐
相关产品推荐

