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

如何在Python中实现类似SQL ORDER BY的多条件排序(含时长计算)

多条件排序TimeSlot列表(模拟SQL ORDER BY duration(till - from), capacity)

原始数据

你拥有的TimeSlot对象列表如下:

time_slots = [
<TimeSlot: number: 1, capacity: 4, advance: 10, from: 02:00:00, till: 08:00:00>,
<TimeSlot: number: 2, capacity: 3, advance: 17, from: 01:00:00, till: 04:00:00>,
<TimeSlot: number: 3, capacity: 3, advance: 17, from: 01:00:00, till: 04:00:00>,
<TimeSlot: number: 4, capacity: 1, advance: 17, from: 03:00:00, till: 08:00:00>,
<TimeSlot: number: 5, capacity: 4, advance: 17, from: 02:00:00, till: 07:00:00>,
<TimeSlot: number: 6, capacity: 3, advance: 17, from: 02:00:00, till: 09:00:00>,
<TimeSlot: number: 7, capacity: 2, advance: 17, from: 03:00:00, till: 08:00:00>
]

需求

实现类似SQL ORDER BY duration(till - from), capacity的排序逻辑:

  • 优先按**时长(till - from)**升序排列
  • 时长相同时,按capacity升序排列

修改冒泡排序实现(适配多条件)

你已实现的冒泡排序仅处理了时长排序,只需修改比较条件,加入capacity的二次判断即可。核心逻辑是:当前一个slot的时长 > 后一个slot的时长,或者时长相等但前一个slot的capacity > 后一个slot的capacity时,交换两者位置。

修改后的代码:

from datetime import date, datetime

def bubbleSort(time_slots):
    swapped = False
    # 预定义日期,用于时间差计算
    base_date = date.today()
    
    for n in range(len(time_slots)-1, 0, -1):
        for i in range(n):
            # 计算当前slot和下一个slot的时长
            slot1_duration = datetime.combine(base_date, time_slots[i].available_till) - datetime.combine(base_date, time_slots[i].available_from)
            slot2_duration = datetime.combine(base_date, time_slots[i+1].available_till) - datetime.combine(base_date, time_slots[i+1].available_from)
            
            # 多条件判断:先比时长,时长相等再比capacity
            if slot1_duration > slot2_duration or (slot1_duration == slot2_duration and time_slots[i].capacity > time_slots[i+1].capacity):
                swapped = True
                time_slots[i], time_slots[i+1] = time_slots[i+1], time_slots[i]
        if not swapped:
            return

bubbleSort(time_slots)

更高效的实现(Python内置sorted函数)

冒泡排序时间复杂度为O(n²),数据量较大时效率较低。推荐使用Python内置的sorted()函数,通过key参数指定排序依据的元组,元组内的元素会按顺序作为排序优先级:

from datetime import date, datetime

base_date = date.today()

def get_sort_key(slot):
    duration = datetime.combine(base_date, slot.available_till) - datetime.combine(base_date, slot.available_from)
    # 返回排序元组:(时长, capacity),默认升序
    return (duration, slot.capacity)

# 生成新的排序后的列表(不修改原列表)
sorted_time_slots = sorted(time_slots, key=get_sort_key)

# 若要直接修改原列表,用list.sort()方法
# time_slots.sort(key=get_sort_key)

这个实现的时间复杂度为O(n log n),远优于冒泡排序,更适合实际业务场景。

内容的提问来源于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 09:08:15