Python cookbook笔记——优先级队列

利用heapq模块实现简单的优先级队列:优先级高的元素优先被pop,相同优先级返回的顺序与它们被插入队列时的顺序相同

队列以元组(-priority, index, item)的形式组成

将priority取负值来时的队列能够按照元素的优先级从高到低排列

index的作用是为了将具有相同优先级的元素以适当顺序排列(因为没有两个元组会有相同的index值,这样python比较两个元组就会到index为止,不会比较两个元组的item),通过维护一个不断递增的索引,元素将以入队列的顺序排列

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]
# how to use it?


class Item:
def __init__(self, name):
self.name = name

def __repr__(self):
return 'Item(%r)' % format(self.name)
# return 'Item({!r})'.format(self.name)

# '%r'或者'{!r}'python中的意思
# >>> a = '123'
# >>> b = 'hello, {!r}'.format(a)
# >>> b
# "hello, '123'"
# 上面的例子用的是format,跟直接%效果类似。


q = PriorityQueue()
q.push(Item('foo'), 1)
q.push(Item('bar'), 5)
q.push(Item('spam'), 4)
q.push(Item('grok'), 1)
for i in range(4):
print(q.pop())

原文地址:https://www.cnblogs.com/QiLF/p/9329563.html