非常抱歉问这样一个愚蠢的问题,但是Python文档让人感到困惑......
链接1:队列实现 http://docs.python.org/library/queue.html
文档中说队列有一个优先级队列的类。但我找不到如何实现它。
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中,哪种优先队列实现方式最有效?以及如何实现它?