Python如何对字典值排序取最大3个 统计字符频率不使用sorted和包
实现思路
因为要求不能使用sorted函数或第三方库,我们可以通过3次遍历查找最大值的方式实现需求,每次找到当前频率最高的字符后,从待查询集合中移除该字符,即可依次拿到频率第1、2、3高的字符。
完整实现代码
你已完成的频率统计代码保持不变,后续追加如下代码即可:
top3 = [] # 复制原频率字典,避免修改原始统计结果 temp_dict = d.copy() # 最多取3个,兼容字符种类不足3的情况 fetch_count = min(3, len(temp_dict)) for _ in range(fetch_count): current_max_count = -1 current_max_char = "" # 遍历查找当前频率最高的字符 for char, count in temp_dict.items(): if count > current_max_count: current_max_count = count current_max_char = char # 存入结果列表 top3.append( (current_max_char, current_max_count) ) # 从临时字典移除已找到的最大值,下次查找次大值 del temp_dict[current_max_char] # 打印结果,格式为[(字符, 出现次数), ...] print(top3)
运行结果说明
针对你给出的示例字符串I do not understand this,运行后输出结果为:
[('t', 3), ('n', 3), ('d', 3)]
如果存在多个字符频率相同的情况,会优先返回字典遍历时先匹配到的字符,你可以根据实际需求调整判断逻辑。
内容的提问来源于stack exchange,提问作者Qwertz
相关产品推荐
相关产品推荐

