python 优先队列

直接上代码
import heapq
arr = [3,2,1,5,8]
heapq.heappush(arr,5)
print(arr)
heapq.heapify(arr)
a = heapq.heappop(arr)
print(arr)
print(a)

  

另一种方法 当一个对象的所有元素都是可比较的时,默认情况下是根据队列中的对象的第一个元素进行排序,越小的优先级越高,排在越前面。当第一个元素相同时,依次比较后续的元素的大小来进行排序。

 

from queue import PriorityQueue

q = PriorityQueue()

# insert into queue
q.put((2, 'g'))
q.put((3, 'e'))
q.put((4, 'k'))
q.put((5, 's'))
q.put((1, 'e'))

# remove and return
# lowest priority item
print(q.get())
print(q.get())

# check queue size
print('Items in queue :', q.qsize())

# check if queue is empty
print('Is queue empty :', q.empty())

# check if queue is full
print('Is queue full :', q.full())

 

posted @ 2022-07-26 16:43  莫大师兄  阅读(654)  评论(0)    收藏  举报