Python 的通用优先级队列 [英] A generic priority queue for Python
本文介绍了Python 的通用优先级队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在我的 Python 代码中使用优先队列,并且:
I need to use a priority queue in my Python code, and:
- 正在寻找优先队列的任何快速实现
- 最理想的是,我希望队列是通用(即适用于具有指定比较运算符的任何对象).
- am looking for any fast implementations for priority queues
- optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).
四处寻找有效的东西,我发现了 heapq,但是:
Looking around for something efficient, I came upon heapq, but:
- 我正在寻找比
heapq
更快的东西,它是用原生 Python 实现的,所以它并不快. - 看起来不错,但似乎只针对整数指定.我想它适用于任何具有比较运算符的对象,但它没有指定它需要什么比较运算符.
- 更新:在
heapq
中重新比较,我可以使用(priority, object)
作为 Charlie Martin 建议,或者只是实现__cmp__
为我的对象.
- I'm looking for something faster than
heapq
, which is implemented in native Python, so it's not fast. - It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs.
- Update: Re comparison in
heapq
, I can either use a(priority, object)
as Charlie Martin suggests, or just implement__cmp__
for my object.
推荐答案
您可以使用 Queue.PriorityQueue.
回想一下,Python 不是强类型的,因此您可以保存任何您喜欢的内容:只需创建一个 (priority, thing)
元组即可.
Recall that Python isn't strongly typed, so you can save anything you like: just make a tuple of (priority, thing)
and you're set.
这篇关于Python 的通用优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文