2022年 11月 7日

pythoncook中实现一个优先级队列(含代码注释)

问题:怎样实现一个按优先级排序的队列?并且在这个队列上面每次pop操作总是返回优先级最高的那个元素

解决方案:

下面的类利用heapq模块实现了一个简单的优先级队列:

  1. # 此为排序序列
  2. import heapq
  3. class PriorityQueue:
  4. def __init__(self):
  5. self._queue = []
  6. self._index = 0
  7. def push(self, item, priority):
  8. # heapq.heappush 将字符按照优先级从高到低插入self.queue列表里
  9. heapq.heappush(self._queue, (-priority, self._index, item))
  10. # 此处的优先级比较方法为先按照元组里第一个元素进行比较,然后再根据第二个元素进行比较,依次类推(此处先比较优先级,在比较插入顺序,在比较字符的大小)
  11. self._index += 1
  12. def pop(self):
  13. # heapq.heappop 弹出并返回最小值
  14. return heapq.heappop(self._queue)[-1]
  15. # 此处的负一目的是只打印最后的字符,否则打印出来的为(5, 1, Item('bar'))

 

  1. # 更改字符格式
  2. class Item:
  3. def __init__(self, name):
  4. self.name = name
  5. def __repr__(self):
  6. return 'Item({!r})'.format(self.name)

下面是它的使用方式:

  1. q = PriorityQueue()
  2. q.push(Item('foo'), 1)
  3. q.push(Item('bar'), 5)
  4. q.push(Item('spam'), 4)
  5. q.push(Item('grok'), 1)
  6. q.pop()
  7. # Item('bar') 因为bar的优先级最高为5
  8. q.pop()
  9. # Item('spam')
  10. q.pop()
  11. # Item('foo') 当优先级一样时按插入顺序进行输出
  12. q.pop()
  13. # Item('grok')