#### 問題:
怎樣實現一個按優先級排序的隊列?并且在這個隊列上面每次 pop 操作總是返回優先級最高的那個元素
#### 解決問題:
下面的類利用 `heapq` 模塊實現了一個簡單的優先級隊列
```python
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
# -priority 越小,優先級越高
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
```
下面是它的使用方式:
```
>>> class Item:
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return 'Item({!r})'.format(self.name)
...
>>> q = PriorityQueue()
>>> q.push(Item('foo'), 1)
>>> q.push(Item('bar'), 5)
>>> q.push(Item('spam'), 4)
>>> q.push(Item('grok'), 1)
>>> q.pop()
Item('bar')
>>> q.pop()
Item('spam')
>>> q.pop()
Item('foo')
>>> q.pop()
Item('grok')
>>>
```
##### 仔細觀察可以發現,第一個`pop()`操作返回優先級最高的元素。另外注意到如果兩個有著相同優先級的元素(`foo`和`grok`),`pop`操作按照它們被插入到隊列的順序返回的。
*****
*****
原文地址:
> https://python3-cookbook.readthedocs.io/zh_CN/latest/c01/p05_implement_a_priority_queue.html