开发者

getting python priority queue return item of largest priority

I am using Queue.Priority class in python 2.7 as below

q=Queue开发者_运维问答.PriorityQueue()
q.put((2,"second"))
q.put((1,"first"))
q.put((3,"third"))
print q.get(True)
print q.get(True)
print q.get(True)

This would return the following result since get() returns the item of lowest priority

(1, 'first')
(2, 'second')
(3, 'third') 

Suppose,I need get to return the item of highest priority .what should I do? Is there a way to do this other than overriding get() method?


If it's just the first element of the tuple that matters, and it's an integer, you could simply negate it:

q=Queue.PriorityQueue()
q.put((-2,"second"))
q.put((-1,"first"))
q.put((-3,"third"))
print q.get(True)
print q.get(True)
print q.get(True)

This will print out:

(-3, 'third') 
(-2, 'second')
(-1, 'first')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜