对不起,这是一个愚蠢的问题,但Python文档令人困惑。如何在Python中实现优先队列?
链接1:Queue实现 http://docs.python.org/library/queue.html
它说,这就是队列具有优先级队列contruct。但我找不到如何实现它。
class Queue.PriorityQueue(maxsize=0)
链接2:堆实现 http://docs.python.org/library/heapq.html
在这里,他们说,我们可以间接使用heapq
pq = [] # list of entries arranged in a heap
entry_finder = {} # mapping of tasks to entries
REMOVED = '<removed-task>' # placeholder for a removed task
counter = itertools.count() # unique sequence count
def add_task(task, priority=0):
'Add a new task or update the priority of an existing task'
if task in entry_finder:
remove_task(task)
count = next(counter)
entry = [priority, count, task]
entry_finder[task] = entry
heappush(pq, entry)
def remove_task(task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
entry = entry_finder.pop(task)
entry[-1] = REMOVED
def pop_task():
'Remove and return the lowest priority task. Raise KeyError if empty.'
while pq:
priority, count, task = heappop(pq)
if task is not REMOVED:
del entry_finder[task]
return task
raise KeyError('pop from an empty priority queue'
在Python里是最有效的优先级队列实现实现优先级队列?以及如何实施它?
[Python的一个普通优先级队列(可能的重复http://stackoverflow.com/questions/407734/a-generic-priority-queue -for-python) – 2017-05-17 14:22:11