heapq模块,可以实现python的堆排序。堆排序的实现是经典的上浮、下沉
用法:
import heapq
scores = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]
# 数组转成最小堆
heap = []
heapq.heapify(scores)
# pop 最小元素
heapq.heappop(scores) # 15
# 往堆里加入元素
heapq.heappush(scores, 9)
# 输出数组中最大的3个元素和最小的2个元素
num_list = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]
print heapq.nlargest(3, num_list) # [91, 87, 82]
print heapq.nsmallest(2, num_list) # [15, 33]