Python中统计嵌套列表字典title值频率及按频率排序的问题
解决方案
1. 获取title的最高出现频率
先修正Counter的使用方式,正确统计所有title的出现次数后提取最大值:
from collections import Counter deet = [ {'title': 'T-90', 'timestamp': '2022-10-08T21:01:51Z'}, {'title': 'Category:17th-century women of the Ottoman Empire', 'timestamp': '2022-10-08T21:01:50Z'}, {'title': 'T-90', 'timestamp': '2022-10-08T21:01:51Z'}, {'title': 'T-90', 'timestamp': '2022-10-08T21:01:51Z'}, {'title': 'T-91', 'timestamp': '2022-10-08T21:01:51Z'} ] # 统计每个title的出现次数 title_counter = Counter(item['title'] for item in deet) # 获取最高出现频率 max_freq = max(title_counter.values()) print(f"最高出现频率: {max_freq}")
运行后会输出最高出现频率: 3,对应示例中T-90的出现次数。
2. 按title频率从高到低重排序原列表
利用已统计的title_counter作为排序依据,通过sorted函数实现排序:
# 按频率降序排序原列表 sorted_deet = sorted(deet, key=lambda x: title_counter[x['title']], reverse=True) # 验证排序结果 for entry in sorted_deet: print(entry['title'])
输出结果会按T-90(3次)、T-91(1次)、Category:17th-century women of the Ottoman Empire(1次)的顺序排列。
报错原因说明
你之前的代码[new["title"] for new in deet].Counter()错误在于列表对象没有Counter方法,正确用法是将title的可迭代对象传入Counter类,创建计数实例。
内容的提问来源于stack exchange,提问作者Casey
相关产品推荐
相关产品推荐

