← 中文资源

简体中文版本

heapq.merge 多路归并已排序序列

heapq.merge 把多路已排序输入惰性归并成一路全局有序输出:reverse=True 支持倒序归并,key= 让结构化记录按字段比较,同优先级保持各路内先后。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

merged: [1, 2, 3, 5, 7, 9, 12, 14, 20]
desc: [9, 8, 5, 4, 1, 0]
events: [('t1', 'api-hit'), ('t2', 'cache-flush'), ('t7', 'api-miss'), ('t9', 'cache-warm')]

实现说明

runs、events 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 跑完文件,输出里会留下标记——merged:、desc:、events:。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 全部导入都来自标准库:heapq。 跨调用保留的状态放在这些顶层绑定里:runs、events。

代码示例

import heapq

# 多路归并:每一路必须已排序,输出全局有序且惰性逐个产出
runs = [
    [3, 7, 12],
    [1, 9, 14],
    [2, 5, 20],
]
print("merged:", list(heapq.merge(*runs)))

# reverse=True 与 sorted 同语义:按倒序归并各路
print("desc:", list(heapq.merge([9, 5, 1], [8, 4, 0], reverse=True)))

# key= 让结构化记录按字段归并(同优先级保持各路内的先后)
events = heapq.merge(
    [("t2", "cache-flush"), ("t9", "cache-warm")],
    [("t1", "api-hit"), ("t7", "api-miss")],
    key=lambda event: event[0],
)
print("events:", list(events))