python优先队列
时间: 2023-08-19 09:17:29 浏览: 118
Python中的优先队列可以使用heapq模块来实现。可以基于heapq来创建一个PriorityQueue类,该类可以实现入队、出队和获取队列大小等操作。[1]另外,也可以参考Python的queue.PriorityQueue类的设计来实现优先队列。[2]在往队列中加入元素时,第一个元素的值表示元素的优先级,值越小优先级越高。通常情况下,队列中的元素类型为元组,这样可以保存多个值。[3]以下是一个具体的例子:
```python
import heapq
class PriorityQueue:
def __init__(self):
self.queue = []
def qsize(self):
return len(self.queue)
def put(self, ele):
heapq.heappush(self.queue, ele)
def get(self):
return heapq.heappop(self.queue)
```
使用示例:
```python
if __name__ == '__main__':
pq = PriorityQueue()
pq.put((100, 100))
pq.put((-12, -7))
pq.put((7, 8))
while pq.qsize() > 0:
print(pq.get())
```
这样就可以实现一个基于小顶堆的优先队列。
阅读全文
相关推荐














