You need to enable JavaScript to run this app. Python如何对字典列表按distance、matches_count双字段自定义排序
优惠活动
大模型
产品
解决方案
定价
更多

Python如何对字典列表按distance、matches_count双字段自定义排序

结论

完全可以通过Python内置的sorted方法实现该排序需求。

实现方案

Python的sorted函数支持通过key参数自定义排序规则,对于多字段不同排序方向的需求,有两种常用实现方式:

方法1:元组Key法(仅适用于数值类型的降序字段)

对于数值类型的matches_count字段,我们可以对其取负值,将降序需求转换为默认的升序逻辑,直接返回排序元组即可:

# 先修正原示例字典的语法错误(原示例部分key缺少引号、引号位置错误)
x = [
    {"matches_count": 10, "distance": 50},
    {"matches_count": 20, "distance": 50},
    {"matches_count": 1, "distance": 20},
    {"matches_count": 2, "distance": 20},
    {"matches_count": 5, "distance": 30},
]

# 核心排序逻辑:先按distance升序,相同distance按matches_count降序
sorted_x = sorted(x, key=lambda item: (item["distance"], -item["matches_count"]))

执行后sorted_x的结果和你给出的预期结果完全一致。

方法2:稳定排序法(通用方案,适配所有字段类型)

如果需要降序排列的字段不是数值类型(比如字符串),可以利用Python排序的稳定性特性,分两次排序:

  1. 先按次要规则(matches_count降序)排序
  2. 再按主要规则(distance升序)排序
    相同distance的元素会保留第一次排序后的相对顺序,最终实现需求:
# 第一步:按matches_count降序排序
temp = sorted(x, key=lambda item: item["matches_count"], reverse=True)
# 第二步:按distance升序排序,稳定排序保留相同distance下的matches_count顺序
sorted_x = sorted(temp, key=lambda item: item["distance"])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 13:45:04