一、通过list建堆
1、heapify()可以把list变成堆
from heapq import *
a=[0,6,3,2]
heapify(a)
while len(a)>0:
print(heappop(a))
2、直接对空list进行heappush操作
b=[]
heappush(b,5)
heappush(b,3)
heappush(b,2)
heappush(b,0)
while len(b)>0:
print(heappop(b))
3、如果list非空,但是是有序的,可以通过heappop和heappush操作
c=[0,2,3,5]
heappush(c,4)
while len(c)>0:
print(heappop(c))
二、pop和push
最普通的heappop和heappush在上面已经演示过了。
heapq还提供了两个函数,为pop和push的合并,这样可以保证堆大小不变且效率更高一些。
heapq.
heappushpop
(heap, item)
heapq.heapreplace
(heap, item)
他们的区别是heappushpop为先push再pop,另一个相反。
三、其他
heapq.
merge
(*iterables, key=None, reverse=False)
合并heap
heapq.
nlargest
(n, iterable, key=None)
输出heap中最大的n个元素
heapq.
nsmallest
(n, iterable, key=None)
输出heap中最小的n个元素
这三个函数返回值都是generator
for i in merge(a,b,c):
print(i)
for i in nlargest(2,c):
print(i)
for i in nsmallest(2,c):
print(i)