如何将项目放入优先级队列?

Jie*_*eng 33 python queue

在Python文档中,

首先检索最低值的条目(最低值条目是返回的条目sorted(list(entries))[0]).条目的典型模式是以下形式的元组:(priority_number, data).

看来队列将按优先级排序,然后按数据排序,这可能并不总是正确的.假设数据"项目2"在"项目1"之前排队,项目1仍将首先排队.在另一个文档页面heapq中,它建议使用计数器.所以我会存储我的数据entry = [priority, count, task].是不是有类似的东西

PriorityQueue.put(item, priority)
Run Code Online (Sandbox Code Playgroud)

那我自己不需要实现订购了吗?

gfo*_*une 33

如果字符串数据的字母数字排序不合适,只需使用元组的第二项作为次要优先级.当您有多个具有相同优先级的项目时,日期/时间优先级将为您提供一个优先级队列,该队列可以回退到FIFIO队列.这是一些只有次要数字优先级的示例代码.在第二个位置使用日期时间值是一个非常微不足道的变化,但如果你无法使它工作,请随时在评论中戳我.

import Queue as queue

prio_queue = queue.PriorityQueue()
prio_queue.put((2, 8, 'super blah'))
prio_queue.put((1, 4, 'Some thing'))
prio_queue.put((1, 3, 'This thing would come after Some Thing if we sorted by this text entry'))
prio_queue.put((5, 1, 'blah'))

while not prio_queue.empty():
    item = prio_queue.get()
    print('%s.%s - %s' % item)
Run Code Online (Sandbox Code Playgroud)

产量

1.3 - This thing would come after Some Thing if we didn't add a secondary priority
1.4 - Some thing
2.8 - super blah
5.1 - blah
Run Code Online (Sandbox Code Playgroud)

编辑

如果您使用时间戳使用日期伪造FIFO作为次要优先级,那么这就是它的样子.我说假,因为它只是近似FIFO,因为彼此非常接近的条目可能不会精确地出现FIFO.我添加了一个简短的睡眠,所以这个简单的例子以合理的方式解决.希望这有助于您获得所需订单的另一个例子.

import Queue as queue
import time

prio_queue = queue.PriorityQueue()
prio_queue.put((2, time.time(), 'super blah'))
time.sleep(0.1)
prio_queue.put((1, time.time(), 'This thing would come after Some Thing if we sorted by this text entry'))
time.sleep(0.1)
prio_queue.put((1, time.time(), 'Some thing'))
time.sleep(0.1)
prio_queue.put((5, time.time(), 'blah'))

while not prio_queue.empty():
    item = prio_queue.get()
    print('%s.%s - %s' % item)
Run Code Online (Sandbox Code Playgroud)


jco*_*ado 29

据我所知,你想要的东西不是开箱即用的.无论如何,请注意,实施起来并不困难:

from Queue import PriorityQueue

class MyPriorityQueue(PriorityQueue):
    def __init__(self):
        PriorityQueue.__init__(self)
        self.counter = 0

    def put(self, item, priority):
        PriorityQueue.put(self, (priority, self.counter, item))
        self.counter += 1

    def get(self, *args, **kwargs):
        _, _, item = PriorityQueue.get(self, *args, **kwargs)
        return item


queue = MyPriorityQueue()
queue.put('item2', 1)
queue.put('item1', 1)

print queue.get()
print queue.get()
Run Code Online (Sandbox Code Playgroud)

示例输出:

item2
item1
Run Code Online (Sandbox Code Playgroud)

  • @larsmans我试过了,但似乎`PriorityQueue`是一个旧的样式类,它不适用于`super`. (3认同)