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

标签 python queue priority-queue

众所周知,插入优先级队列的元素有一个值,该值决定了它的优先级。例如,如果我有五个具有优先级的元素 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.

关于python - 具有两个优先级值的优先级队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25232722/

相关文章:

Python - 将递归抽象为所有第 n 级递归(lxml)

python - Plotly:如何在 plotly express 折线图中更改图例的变量/标签名称?

java - 响应式(Reactive)编程和消息队列的区别

java - 在 ActiveMQ 中存储和处理消息

java - 为优先级队列提供更多元素?

c# - 如何高效地重建 FIFO PriorityQueue 内存索引

c++ - 从 std::priority_queue 派生的类不使用比较器谓词/模板参数

不使用但仍从函数返回的变量的 Python 约定

python - 基于索引的python列表中的优雅切片

Python 线程队列与多处理管道