官方文档地址: heapq
heapq模块实现了一个非常有效率的堆结构。该结构用list来实现,并采用一种常见的编码形式:如果a[i]的子节点就位于a[2*i+1]和a[2*i+2]这两个位置。a[0]是最小的元素。
创建一个堆只需要从一个空列表开始。当把一个lIst转成堆结构,需要用到函数heaplfy,这是一个线性操作。
主要函数:
heappush(heap,item):加入一个元素到item中
heappop(heap):丢出一个元素,一般是最小的元素,就是a[0]
heaplfy(list):列表转成堆结构
简单的创建和heappop验证:
from heapq import heappop,heappush
from random import randrange
q=[]
for i in range(10):
heappush(q,randrange(100))
print(q)
while q:
a = heappop(q)
print(a)
好、输出的数据是:
[1, 40, 24, 46, 54, 48, 87, 76, 69, 94]
1
24
40
46
48
54
69
76
87
94
第一行是创建的堆,以列表形式显现,下面是追个pop出,可以看到,是从最小的开始的。
同时,heap也可以用于优先级队列(priority queue)正确地插值。
from heapq import heappop,heappush
from random import randrange
heap=[]
data = [(1,'a'),(6,'z'),(2,'b'),(4,'e')]
for item in data:
heappush(heap,item)
heappush(heap,(3,'g'))
while heap:
print(heappop(heap))
输出为:
(1, 'a')
(2, 'b')
(3, 'g')
(4, 'e')
(6, 'z')
另外,还有一些其他函数,基于这个模块。
heap.merge(*iterable)
Merge multiple sorted inputs into a single sorted output (for example, mergetimestamped entries from multiple log files). Returns an iteratorover the sorted values.
heapq.nlargest:
Return a list with the n largest elements from the dataset defined byiterable.
heapq.nsmallest