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

如何合并工作日时间段字典中值重复的条目并按时间段分组

实现方案

核心逻辑:嵌套列表属于不可哈希类型,无法直接作为字典键做反转分组,我们可以将时间段的嵌套列表转换为可哈希的元组作为临时分组键,即可实现按相同时间段聚合工作日的需求。

代码实现(Python)

def merge_same_time_slots(week_time_dict):
    # 临时存储分组结果,key为时间段转成的可哈希元组
    time_group = {}
    for day_str, time_spans in week_time_dict.items():
        # 把嵌套列表转成元组,作为分组唯一键
        group_key = tuple(tuple(span) for span in time_spans)
        # 不存在该分组则初始化
        if group_key not in time_group:
            time_group[group_key] = {
                "weekdays": [],
                "time_spans": time_spans
            }
        # 字符串格式的工作日转整数后加入对应分组
        time_group[group_key]["weekdays"].append(int(day_str))
    # 提取分组的值转为列表即为最终结果
    return list(time_group.values())

# 测试示例
if __name__ == "__main__":
    input_dict = {
        "0": [["09:00:00", "12:00:00"]],
        "1": [["09:00:00", "12:00:00"]],
        "2": [["09:00:00", "12:00:00"], ["12:30:00", "15:30:00"]],
        "3": [["09:00:00", "12:00:00"]],
        "4": [["09:00:00", "12:00:00"]],
        "5": [["09:00:00", "12:00:00"], ["12:30:00", "15:30:00"]],
        "6": [["09:00:00", "12:00:00"], ["12:30:00", "15:30:00"]]
    }
    print(merge_same_time_slots(input_dict))

扩展说明

如果你的业务场景中,时间段顺序不同但内容完全一致也视为相同时间段,可以在生成分组键前先对时间段做排序处理,修改生成group_key的代码即可:

# 先排序再转元组,适配时间段顺序无关的场景
sorted_spans = sorted(time_spans)
group_key = tuple(tuple(span) for span in sorted_spans)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:18:02