代码:
import heapq
import random
def issorted(data):
data = list(data)
heapq.heapify(data)
while data:
yield heapq.heappop(data)
alist = [x for x in range(10)]
random.shuffle(alist)
print 'the origin list is',alist
print 'the min in the list is'
for x in issorted(alist):
print x,
the origin list is [4, 3, 9, 0, 7, 2, 1, 6, 5, 8]
the min in the list is
0 1 2 3 4 5 6 7 8 9
使用了heapq模块和random模块.heapq二叉树,常用来处理优先级序列问题。
还有一个更为简单的方法:
print heapq.nsmallest(3,alist) #打印出alist列表中最小的三个元素 最小,如果是字母就是按字母序比较