优先级队列底层使用的是堆结构,如果升序排列就对应小顶堆,降序排列对应大顶堆。
主要操作:
import heapq as hq
end=[]
hq.heapify(end)
hq.heappush(end,2)
hq.heappush(end,3)
hq.heappush(end,1)
while len(end)!=0:
print(hq.heappop(end),end=' ')
如果想要设置优先级可以使用元组(),在第一个位置写入数字来指定优先级,其原理就是优先级队列排序是从前向后比较,并使用升序排列.
指定优先级:
import heapq as hq
end=[]
hq.heapify(end)
hq.heappush(end,(3,[3,2]))
hq.heappush(end,(2,[2,3]))
hq.heappush(end,(1,[1,3]))
while len(end)!=0:
print(hq.heappop(end)[1])#只要数据
import heapq as hq
end=[]
hq.heapify(end)
res=[1,3,2,4,8,5,6]
for i in range(0,len(res)):
hq.heappush(end,(-res[i],res[i]))
while len(end)!=0:
print(hq.heappop(end)[1],end=' ')
import heapq as hq
res=list(hq.merge([12,3,4,2],[1,2,9,2],[90]))
print(res)
总体实现方法和heapq类似
import queue
p=queue.PriorityQueue()
p.put(1)
p.put(3)
p.put(2)
print(p.qsize())
for i in range(0,3):
print(p.get(),end=' ')
print()
print(p.qsize())