Can I get an item from a PriorityQueue without removing it yet?

流过昼夜 提交于 2019-12-21 07:04:27

问题


I want to get the next item in queue but I don't want to dequeue it. Is it possible in Python's Priority Queue? From the docs, I don't see how can it be done


回答1:


When you get item form the queue as per theory it will remove from the queue. You have to write your own function which will give you last element of PriorityQueue. You can create a peek function by inherit the priorityqueue.




回答2:


If a is a PriorityQueue object, You can use a.queue[0] to get the next item:

from Queue import PriorityQueue

a = PriorityQueue()

a.put((10, "a"))
a.put((4, "b"))
a.put((3,"c"))

print a.queue
print a.get()
print a.queue
print a.get()
print a.queue

output is :

[(3, 'c'), (10, 'a'), (4, 'b')]
(3, 'c')
[(4, 'b'), (10, 'a')]
(4, 'b')
[(10, 'a')]

but be careful about multi thread access.




回答3:


If you want next element in the PriorityQueue, in the order of the insertion of the elements, use:

for i in range(len(queue)):
    print queue.queue[i]

this will not pop anything out.

If you want it in the priority order, use:

for i in range(len(queue)):
    temp = queue.get()
    queue.put(temp)
    print temp

If you are using a tuple, instead of a single variable, replace temp by:

((temp1,temp2))



回答4:


Assuming your items stored in the PriorityQueue is a tuple (key, value),

def peak(pq):
  return pq.queue[0][1] 



回答5:


Indexing the first element of the queue should work. If you're using the heapq library, the document mentions:

The interesting property of a heap is that its smallest element is always the root, heap[0].



来源:https://stackoverflow.com/questions/9287919/can-i-get-an-item-from-a-priorityqueue-without-removing-it-yet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!