如何遍历优先队列? [英] How to iterate over a Priority Queue?

查看:284
本文介绍了如何遍历优先队列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Python 中实现 Uniform-cost search那,我需要一个优先级队列,我正在使用 queue.py来自标准库.但是,算法的末尾会检查队列中是否存在任何成本较高的路径.如果它不可迭代,我如何检查我的队列中是否有任何给定的值?

解决方案

queue.PriorityQueue 实际上是使用 list 实现的,put>/get 方法使用 heapq.heappush/heapq.heappop 来维护 list 中的优先级排序.因此,如果您愿意,您可以遍历包含在 queue 属性中的内部列表:

<预><代码>>>>从队列导入PriorityQueue>>>q = PriorityQueue()>>>q.put((5, "a"))>>>q.put((3, "b"))>>>q.put((25, "c"))>>>q.put((2, "d"))>>>打印(q.queue)[(2, 'd'), (3, 'b'), (25, 'c'), (5, 'a')]

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')]

这篇关于如何遍历优先队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆