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

Python实现数值列表按时间槽聚合及缺失槽最大值补全方案

实现方案

核心思路

  • 先把输入字符串解析为整数格式的unit和timestamp,避免字符串比较的逻辑错误
  • 用timestamp // 10 * 10直接计算每个时间戳所属的10间隔槽位,将同槽位的unit统一分组
  • 先计算所有有数据槽位的unit最大值,再从最小槽位到最大槽位遍历所有连续间隔,无数据的槽位直接继承上一个槽位的最大值

完整可运行代码

units_to_parse = '2:0,1:9,5:10,2:12,4:19,5:35'

def parse_units(units_str):
    # 解析输入,按时间槽分组存储unit
    slot_units = {}
    for pair in units_str.split(','):
        unit, ts = pair.split(':')
        unit = int(unit.strip())
        ts = int(ts.strip())
        # 计算当前时间所属的10间隔槽位
        slot = ts // 10 * 10
        slot_units.setdefault(slot, []).append(unit)
    
    # 计算所有有数据槽位的最大值
    slot_max_map = {slot: max(unit_list) for slot, unit_list in slot_units.items()}
    
    # 补全缺失槽位
    min_slot = min(slot_max_map.keys())
    max_slot = max(slot_max_map.keys())
    last_max = None
    result = {}
    for slot in range(min_slot, max_slot + 1, 10):
        current_max = slot_max_map.get(slot, last_max)
        result[slot] = current_max
        last_max = current_max
    
    # 按要求格式输出
    output_str = ' '.join([f"{{{slot}: {max_val}}}" for slot, max_val in result.items()])
    print(output_str)
    return result

if __name__ == '__main__':
    parse_units(units_to_parse)

运行输出

{0: 2} {10: 5} {20: 5} {30: 5}

补充说明

如果需要强制从0槽开始补全(哪怕第一个有数据的槽晚于0),只需要把min_slot = min(slot_max_map.keys())改成min_slot = 0即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:27:02