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

如何修正Python字典多条件排序代码:数值降序+同值字母升序

Python字典排序问题修正

问题背景

原始字典:

dic_kol={"History :":2,"Horror :": 2 ,"Adventure :":1 ,"Comedy :":2 ,"Romance :":2 ,"Action :":3}

需求:对字典项排序,规则为先按数值降序,数值相同时按键的字母升序,期望输出:

[('Action :', 3), ('Comedy :', 2), ('History :', 2), ('Horror :', 2), ('Romance :', 2), ('Adventure :', 1)]

当前错误代码:

print(sorted(dic_kol.items(),key=lambda x: (x[1],x[0]),reverse=True))

错误输出:

[('Action :', 3), ('Romance :', 2), ('Horror :', 2), ('History :', 2), ('Comedy :', 2), ('Adventure :', 1)]

问题原因

使用reverse=True会对整个排序键元组(x[1], x[0])进行降序排列,导致数值相同时,键也按降序排序,违背了“字母升序”的要求。

修正方案

调整排序键,将数值取负数,让排序逻辑变为:

  1. 按-x[1]升序(等价于原数值降序)
  2. 数值相同时,按x[0]升序

修正后的代码:

print(sorted(dic_kol.items(), key=lambda x: (-x[1], x[0])))

执行后即可得到符合要求的排序结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:57:03