一组有序序列,想对它们合并在一起之后的有序序列进行迭代
import heapq
a = [1, 1, 7, 10]
b = [2, 5, 6, 11]
for c in heapq.merge(a, b):
print(c, end='') # 1125671011
with open('sorted_file_1.txt', 'rt') as file1, \
open('sorted_file_2.txt', 'rt') as file2, \
open('merged_file.txt', 'wt') as outf:
for line in heapq.merge(file1, file2):
outf.write(line)
heapq.merge()要求所有的输入序列都是有序的。它只是简单地检查每个输入序列中的第一个元素,将最小的那个发送出去。