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

如何对索引关联的嵌套列表先按日期再按时间排序并获取正确索引序列

解决方案

要解决这个按「日期优先、时间次之」排序并提取索引序列的问题,核心是先通过索引关联两个列表的对应元素,再组合排序规则完成排序。以下是具体实现步骤:

  1. 将列表转为索引映射字典
    把date_list和time_list转换成以索引为键的字典,方便快速通过索引获取对应的日期和时间:

    date_list = [[b'05-07-2024', 0], [b'16-08-2024', 1], [b'16-08-2024', 2]]
    time_list = [[b'15-20-55', 2], [b'15-21-00', 0], [b'23-41-01', 1]]
    
    # 构建索引到日期的映射(字节串转字符串方便拆分处理)
    date_map = {idx: date.decode('utf-8') for date, idx in date_list}
    # 构建索引到时间的映射
    time_map = {idx: time.decode('utf-8') for time, idx in time_list}
    
  2. 定义排序键函数
    原日期格式是dd-mm-yyyy,直接字符串排序会逻辑错误,需要拆分为(年, 月, 日)的整数元组;时间格式hh-mm-ss可直接拆分为(时, 分, 秒)的整数元组,以此作为排序依据:

    def sort_key(idx):
        # 处理日期:转换为年、月、日的整数元组
        day, month, year = date_map[idx].split('-')
        date_tuple = (int(year), int(month), int(day))
        # 处理时间:转换为时、分、秒的整数元组
        hour, minute, second = time_map[idx].split('-')
        time_tuple = (int(hour), int(minute), int(second))
        # 先按日期排序,日期相同时按时间排序
        return (date_tuple, time_tuple)
    
  3. 对索引排序并输出结果
    提取所有索引,用自定义键函数完成排序:

    # 获取所有索引集合
    indices = list(date_map.keys())
    # 按规则排序
    sorted_indices = sorted(indices, key=sort_key)
    print(sorted_indices)  # 输出: [0, 2, 1]
    

补充说明

  • 如果你的环境中字节串可以直接拆分处理,也可以跳过decode('utf-8')步骤;
  • Python的sorted函数会自动先比较日期元组,只有当日期完全相同时,才会对比时间元组,完全匹配需求逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:33:25