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

如何计算字典列表中各工序的最大间隙并提取为新字典

提取各工序的最大时间间隙

原始数据如下:

data = [
{'order': 1, 'operation': 'milling', 'duration': 70, 'position': 1, 'start': 0, 'end': 70},
{'order': 1, 'operation': 'milling', 'duration': 20, 'position': 2, 'start': 200, 'end': 210},
{'order': 1, 'operation': 'milling', 'duration': 100, 'position': 2, 'start': 500, 'end': 600},
{'order': 1, 'operation': 'grinding', 'duration': 60, 'position': 3, 'start': 90, 'end': 150},
{'order': 2, 'operation': 'grinding', 'duration': 20, 'position': 1, 'start': 150, 'end': 170},
{'order': 3, 'operation': 'grinding', 'duration': 20, 'position': 1, 'start': 400, 'end': 420},
{'order': 3, 'operation': 'milling', 'duration': 50, 'position': 1, 'start': 610, 'end': 660}
]

需求:计算每个工序的最大时间间隙,最终输出格式如下:

max_gaps = [
{'operation': 'milling', 'max_gap': 290, 'start': 210, 'end': 500},
{'operation': 'grinding', 'max_gap': 230, 'start': 170, 'end': 400}
]

实现步骤

  • 按工序分组,同时确保每组内的操作按开始时间排序
  • 遍历每组排序后的操作,计算相邻操作的时间间隙(下一个操作的start减去上一个操作的end)
  • 记录每组的最大间隙及其对应的起止时间
  • 整理成目标格式的字典列表

代码实现

from itertools import groupby

# 按工序+开始时间排序,保证同一工序的操作按时间先后排列
sorted_data = sorted(data, key=lambda x: (x['operation'], x['start']))
# 按工序分组
operation_groups = groupby(sorted_data, key=lambda x: x['operation'])

max_gaps = []
for op, items in operation_groups:
    item_list = list(items)
    # 初始化当前工序的最大间隙信息
    current_max = {
        'operation': op,
        'max_gap': 0,
        'start': 0,
        'end': 0
    }
    # 遍历相邻操作计算间隙
    for i in range(1, len(item_list)):
        prev_end = item_list[i-1]['end']
        curr_start = item_list[i]['start']
        gap = curr_start - prev_end
        # 更新最大间隙信息
        if gap > current_max['max_gap']:
            current_max['max_gap'] = gap
            current_max['start'] = prev_end
            current_max['end'] = curr_start
    max_gaps.append(current_max)

# 输出结果
print(max_gaps)

代码说明

  1. 排序与分组:先通过sorted确保同一工序的操作按时间顺序排列,再用groupby将同一工序的操作归为一组
  2. 间隙计算:遍历每组内的操作,依次计算相邻操作的时间间隔,对比后保留最大的间隙及其起止时间
  3. 结果整理:将每个工序的最大间隙信息封装为字典,最终组成目标格式的列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:27:31