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

如何在Python中实现类似SQL ORDER BY的多字段排序功能?

按number和capacity排序TimeSlot列表(Python实现)

要实现类似SQL中ORDER BY number, capacity的排序逻辑——先按number升序排列,当number相同时再按capacity升序排列,Python里可以通过以下两种方式实现:

方法一:使用sorted()函数(返回新列表)

sorted()函数会生成排序后的新列表,不会修改原列表:

# 按number升序,再按capacity升序排序
sorted_time_slots = sorted(time_slots, key=lambda slot: (slot.number, slot.capacity))

方法二:使用列表的sort()方法(原地排序)

sort()方法会直接修改原列表,无需额外接收返回值:

# 原地完成排序,规则同前
time_slots.sort(key=lambda slot: (slot.number, slot.capacity))

排序逻辑说明

lambda表达式返回的元组(slot.number, slot.capacity)作为排序依据:Python会先比较元组的第一个元素(number),仅当两个元素的number相等时,才会比较第二个元素(capacity),完全匹配SQL的多字段排序规则。

如果需要调整排序方向(比如number降序),可以对对应字段取反:

# 按number降序,capacity升序排序
sorted_time_slots = sorted(time_slots, key=lambda slot: (-slot.number, slot.capacity))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 08:52:19