需求与方案系列
Q:怎样实现一个按优先级排序的队列?并且这个队列每次pop操作总是返回优先级最高的元素?
A:
可以使用heapq模块实现一个简单的优先级队列:
import heapq
class PriorityQueue():
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, 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('horn'), 3)
q.push(Item('spam'), 4)
q.push(Item('grok'), 2)
q.push(Item('eg'), 3)
print(q.pop()) # Item('bar')
print(q.pop()) #Item('spam')
print(q.pop()) # Item('horn')
print(q.pop()) # Item('eg')
print(q.pop()) # Item('grok')
print(q.pop()) # Item('foo')
仔细观察可以发现,第一个pop()操作返回优先级最高的元素。另外注意到如果两个有着相同优先级的元素(horn和eg),pop操作按照他们被插入到队列的顺序返回。