Heapq Merge Combines Sorted Streams

heapq.merge k-way merges already-sorted iterables lazily, honoring reverse and key, so multiple ordered sources yield one ordered sequence.

PythonData Integrity

Code

pythonsnippet
20 lines
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))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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')]

How it works

heapq.merge(*runs) performs a multiway merge: every input must already be sorted, and the merged result is produced lazily, one item at a time — each list(...) call here just drains the merge so it can be printed. reverse=True means what it means in sorted: inputs ordered descending, output descending. The key= form merges structured records by a field, here event[0]; when two events share a key, the one from the earlier argument stream is yielded first, so per-stream order survives ties.

What to watch for

  • heapq ships with the Python standard library — the import needs no package install.

The operative line:

key=lambda event: event[0],

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`heapq` is a standard-library module — it comes with Python itself, nothing to install.