问题描述
我正在尝试在 Python 中实现 Uniform-cost search那,我需要一个优先级队列,我正在使用 queue.py来自标准库.但是,算法的末尾会检查队列中是否存在任何成本较高的路径.如果它不可迭代,我如何检查我的队列中是否有任何给定的值?
queue.PriorityQueue
实际上是使用 list
实现的,put
>/get
方法使用 heapq.heappush
/heapq.heappop
来维护 list
中的优先级排序.因此,如果您愿意,您可以遍历包含在 queue
属性中的内部列表:
I'm trying to implement the Uniform-cost search in Python and for that, I need a priority queue, which I'm using queue.py from the standard library. However, the end of the algorithm checks if there is any path with a higher cost in the queue. How can I check if there is any given value in my queue if it's not iterable?
queue.PriorityQueue
is actually implemented using a list
, and the put
/get
methods use heapq.heappush
/heapq.heappop
to maintain the priority ordering inside that list
. So, if you wanted to, you could just iterate over the internal list, which is contained in the queue
attribute:
>>> from queue import PriorityQueue
>>> q = PriorityQueue()
>>> q.put((5, "a"))
>>> q.put((3, "b"))
>>> q.put((25, "c"))
>>> q.put((2, "d"))
>>> print(q.queue)
[(2, 'd'), (3, 'b'), (25, 'c'), (5, 'a')]
这篇关于如何遍历优先队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!