实现说明
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))