python 堆排序

第一个元素一定是最小的,如果每次只想拿到列表的最小值,不想整个列表排序,可以通过不断返回最小值的方法实现

from heapq import heapify, heappop, heappush
data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapify(data)                      # rearrange the list into heap order
heappush(data, -5)                 # add a new entry
heappush(data, -66)
c=[heappop(data) for i in range(3)]  # fetch the three smallest entries
print(c)
print(data)

原文地址:https://www.cnblogs.com/sea-stream/p/10008353.html