1 parent ac00903 commit 5fccb54Copy full SHA for 5fccb54
2 files changed
cookbook/c04/p15_merge_sorted.py
@@ -0,0 +1,27 @@
1
+#!/usr/bin/env python
2
+# -*- encoding: utf-8 -*-
3
+"""
4
+Topic: sample
5
+Desc :
6
7
+import heapq
8
+
9
10
+def merge_sorted():
11
+ a = [1, 4, 7, 10]
12
+ b = [2, 5, 6, 11]
13
+ for c in heapq.merge(a, b):
14
+ print(c)
15
16
+ # 合并排序文件
17
+ with open('sorted_file_1', 'rt') as file1, \
18
+ open('sorted_file_2', 'rt') as file2, \
19
+ open('merged_file', 'wt') as outf:
20
21
+ for line in heapq.merge(file1, file2):
22
+ outf.write(line)
23
24
25
+if __name__ == '__main__':
26
+ merge_sorted()
27
source/c04/p15_iterate_in_sorted_order_over_merged_sorted_iterables.rst
@@ -5,14 +5,49 @@
----------
问题
-todo...
+你有一系列排序序列,想将它们合并后得到一个排序序列并在上面迭代遍历。
+|
解决方案
+``heapq.merge()`` 函数可以帮你解决这个问题。比如:
+.. code-block:: python
+ >>> import heapq
+ >>> a = [1, 4, 7, 10]
+ >>> b = [2, 5, 6, 11]
+ >>> for c in heapq.merge(a, b):
+ ... print(c)
+ ...
+ 1
+ 2
+ 4
28
+ 5
29
+ 6
30
+ 7
31
+ 10
32
+ 11
33
34
35
36
讨论
37
38
+``heapq.merge`` 可迭代特性意味着它不会立马读取所有序列。
39
+这就意味着你可以在非常长的序列中使用它,而不会有太大的开销。
40
+比如,下面是一个例子来演示如何合并两个排序文件:
41
42
43
44
45
46
47
48
49
50
51
+有一点要强调的是 ``heapq.merge()`` 需要所有输入序列必须是排过序的。
52
+特别的,它并不会预先读取所有数据到堆栈中或者预先排序,也不会对输入做任何的排序检测。
53
+它仅仅是检查所有序列的开始部分并返回最小的那个,这个过程一直会持续直到所有输入序列中的元素都被遍历完。
0 commit comments