Skip to main content
 首页 » 编程设计

python之具有两个优先级值的优先级队列

2025年05月04日13cloudgamer

众所周知,插入优先级队列的元素有一个值,该值决定了它的优先级。例如,如果我有五个具有优先级的元素 A,B,C,D,E(我们将此优先级值称为 priorityI): A = 10,B = 5,C = 1,D = 3,E = 2。 但是我如何编写一个优先级队列,我可以在其中定义两个优先级值,我的意思是: 如果两个元素具有相同的 priorityI 值,则值 priorityII 决定应首先采用哪个元素,例如:

element A has priorityI = 3, and prioriotyII = 5 
element B has priorityI = 3, and prioriotyII = 1 

然后首先从队列中取出第一个元素B。

请您参考如下方法:

从Python2.6开始,可以使用Queue.PriorityQueue .

插入队列的项目根据其 __cmp__ 排序方法,因此只需为其对象要插入队列的类实现一个即可。

请注意,如果您的项目由对象元组组成,则不需要为元组实现容器类,因为 built in tuple comparison implementation可能符合您的需求,如上所述(首先弹出值(value)较低的项目)。但是,您可能需要为其对象驻留在元组中的类实现 __cmp__ 方法。

>>> from Queue import PriorityQueue 
>>> priority_queue = PriorityQueue() 
>>> priority_queue.put((1, 2)) 
>>> priority_queue.put((1, 1)) 
>>> priority_queue.get() 
(1, 1) 
>>> priority_queue.get() 
(1, 2) 

EDIT: As @Blckknght noted, if your priority queue is only going to be used by a single thread, the heapq module, available from Python2.3, is the preferred solution. If so, please refer to his answer.