创建 python 优先级队列
我想在 python 中构建一个优先级队列,其中队列包含不同的字典及其优先级编号。因此,当调用“get函数”时,优先级最高(编号最低)的字典将从队列中拉出,而当调用“add函数”时,新字典将被添加到队列中并根据其排序优先号码。
请帮忙...
提前致谢!
I would like to build a priority queue in python in which the queue contains different dictionaries with their priority numbers. So when a "get function" is called, the dictionary with the highest priority(lowest number) will be pulled out of the queue and when "add function" is called, the new dictionary will be added to the queue and sorted based on its priority number.
Please do help out...
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用标准库中的heapq模块。
您没有指定如何将优先级与字典关联起来,但这里有一个简单的实现:
Use the heapq module in the standard library.
You don't specify how you wanted to associate priorities with dictionaries, but here's a simple implementation:
这是我在一些模式演讲中通常作为旁注呈现的内容:
OP 的要求显然是使用
operator.itemgetter('priority')
作为key
参数实例化PriorityQueue
时(当然需要在模块顶部有一个导入运算符
;-)。This is what I usually present as a side note in some of my patterns talks:
The OP's requirements are apparently to use
operator.itemgetter('priority')
as thekey
argument when instantiatingPriorityQueue
(needs animport operator
at top of module, of course;-).您可以通过向类添加一个 dict 对象并在内部搜索它来完成此操作。
You can do this by adding a dict object to the class, and search it inside.