只要列表没有排序,就继续用迭代器与其自身合并来替换它.这是(相当于)一种常见的排序算法,只是奇怪地实现了,还是有什么新东西?
from random import shuffle
from heapq import merge
from itertools import pairwise
# Create test data
a = list(range(100))
shuffle(a)
# Sort
while any(x > y for x, y in pairwise(a)):
it = iter(a)
a = list(merge(it, it))
print(a)
heapq.merge
确实以"标准"的方式合并了两个输入,但这是一个实现细节,它的输入应该是排序的,但它们不在这里(它们也不是独立的,因为它们使用相同的源).为了消除它作为一个实现细节,让merge
实际上是这样(标准方法,总是比较两个"当前"值,得到较小的一个并获取它的替代):
def merge(xs, ys):
none = object()
x = next(xs, none)
y = next(ys, none)
while (x is not none) and (y is not none):
if x <= y:
yield x
x = next(xs, none)
else:
yield y
y = next(ys, none)
if x is not none:
yield x
if y is not none:
yield y
yield from xs
yield from ys