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

如何按'type'='X'对应的hour值拆分字典列表,生成指定结构的结果字典

解法

单次遍历原列表即可完成转换,时间复杂度为O(n),适配两个X之间任意长度的间隔场景:

完整可运行代码

# 原始数据
list_of_dicts = [
    {"type": "X", "hour": 22},
    {"type": "A", "measure": "1"},
    {"type": "B", "measure": "2"},
    {"type": "X", "hour": 23},
    {"type": "A", "measure": "3"},
    {"type": "X", "hour": 24},
    {"type": "A", "measure": "4"},
    {"type": "B", "measure": "5"},
    {"type": "C", "measure": "6"}
]

# 处理逻辑
dict_of_dicts = {}
current_hour = None
temp_list = []

for item in list_of_dicts:
    if item["type"] == "X":
        # 上一个X对应的中间条目已收集完成,存入结果字典
        if current_hour is not None:
            dict_of_dicts[current_hour] = temp_list
        # 更新当前关联的hour,重置临时存储列表
        current_hour = item["hour"]
        temp_list = []
    else:
        # 收集两个X之间的非X条目
        temp_list.append(item)
# 存入最后一个X对应的所有后续条目
if current_hour is not None:
    dict_of_dicts[current_hour] = temp_list

# 输出验证
print(dict_of_dicts)

运行后输出的dict_of_dicts与你给出的预期结果完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:57:02