How to put items into priority queues?

后端 未结 3 1163
無奈伤痛
無奈伤痛 2020-12-23 16:57

In the Python docs,

The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]

3条回答
  •  既然无缘
    2020-12-23 17:22

    As far as I know, what you're looking for isn't available out of the box. Anyway, note that it wouldn't be hard to implement:

    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()
    

    Example output:

    item2
    item1
    

提交回复
热议问题