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

如何将Python嵌套列表先按数字降序再按字母升序排序

问题原因

你直接使用sorted(l, reverse=True)不符合预期的核心原因是:reverse=True会对整个子列表的对比结果做全局反转,数字降序的要求满足了,但第二个字符串元素也会同步变成降序排列,和你要求的字符串升序规则冲突。

最优解决方案

使用sorted的key参数自定义排序规则即可,利用Python元组按位对比的特性,构造排序键为(-子列表第一个元素, 子列表第二个元素),排序时使用默认的升序规则,就能刚好满足你的要求:

  • 第一个元素取负后,原数值越大负数值越小,升序排列时就会排在更前面,实现数字降序
  • 第二个元素直接用原字符串,升序排列就实现字母顺序升序

完整可运行代码

l = [[2, 'Horror'], [2, 'Romance'], [2, 'Comedy'], [3, 'Action'], [1, 'Adventure'], [2, 'History']]
# 自定义排序key
result = sorted(l, key=lambda x: (-x[0], x[1]))
print(result)

输出结果

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

可选方案:自定义比较函数

如果你更习惯写显式的比较逻辑,可以借助functools.cmp_to_key实现:

from functools import cmp_to_key

l = [[2, 'Horror'], [2, 'Romance'], [2, 'Comedy'], [3, 'Action'], [1, 'Adventure'], [2, 'History']]

def custom_compare(item1, item2):
    # 先对比数字,降序
    if item1[0] != item2[0]:
        return item2[0] - item1[0]
    # 数字相等时对比字符串,升序
    if item1[1] < item2[1]:
        return -1
    elif item1[1] > item2[1]:
        return 1
    else:
        return 0

result = sorted(l, key=cmp_to_key(custom_compare))
print(result)

输出结果和上面的方案完全一致,该方案可读性更高但性能略低于key方案,适合排序逻辑复杂的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:36:05