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

求助:如何对含相同键的字典列表进行多条件排序?

多字典按多键值排序解决方案

假设你有如下结构的字典列表(以Python为例):

dict_list = [
    {'score': 85, 'age': 22},
    {'score': 90, 'age': 20},
    {'score': 85, 'age': 21},
    {'score': 95, 'age': 19}
]

要实现先按第一个键(比如score)排序,值相等时按第二个键(比如age)排序,直接用Python内置的sorted()函数,通过key参数指定排序依据即可:

升序排序(默认)

sorted_list = sorted(dict_list, key=lambda x: (x['score'], x['age']))

执行后输出的排序结果会先按score从小到大排列,score相同的字典再按age从小到大排列:

[
    {'score': 85, 'age': 21},
    {'score': 85, 'age': 22},
    {'score': 90, 'age': 20},
    {'score': 95, 'age': 19}
]

混合升降序(比如score降序,age升序)

如果需要第一个键降序、第二个键升序,只需对第一个键的值取负:

sorted_list = sorted(dict_list, key=lambda x: (-x['score'], x['age']))

结果会优先按score从高到低排列,同分数的按age从小到大排列:

[
    {'score': 95, 'age': 19},
    {'score': 90, 'age': 20},
    {'score': 85, 'age': 21},
    {'score': 85, 'age': 22}
]

原理说明

sorted()的key参数接受一个匿名函数(lambda),返回一个元组。排序时会先比较元组的第一个元素,若相等则比较第二个元素,以此类推,完全匹配你的排序需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:18:08