如何将项目放入优先队列? [英] How to put items into priority queues?

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

问题描述

在 Python 文档中,

In the Python docs,

首先检索最低值的条目(最低值的条目是由 sorted(list(entries))[0] 返回的条目).条目的典型模式是以下形式的元组:(priority_number, data).

The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]). A typical pattern for entries is a tuple in the form: (priority_number, data).

似乎队列将按优先级排序,然后按数据排序,这可能并不总是正确的.假设数据项目 2"排在项目 1"之前,项目 1 仍将排在最前面.在另一个文档页面中,heapq,它建议使用计数器.所以我会像entry = [priority, count, task]那样存储我的数据.有没有类似的东西

It appears the queue will be sorted by priority then data, which may not be always correct. Suppose data "item 2", is enqueued before "item 1", item 1 will still go first. In another docs page, heapq, it suggests the use of a counter. So I will store my data like entry = [priority, count, task]. Isn't there something like

PriorityQueue.put(item, priority)

那我就不需要自己实现排序了吗?

Then I won't need to implement the ordering myself?

推荐答案

据我所知,您正在寻找的内容不是现成的.无论如何,请注意实施起来并不难:

As far as I know, what you're looking for isn't available out of the box. Anyway, note that it wouldn't be hard to implement:

from Queue import PriorityQueue

class MyPriorityQueue(PriorityQueue):
    def __init__(self):
        PriorityQueue.__init__(self)
        self.counter = 0

    def put(self, item, priority):
        PriorityQueue.put(self, (priority, self.counter, item))
        self.counter += 1

    def get(self, *args, **kwargs):
        _, _, item = PriorityQueue.get(self, *args, **kwargs)
        return item


queue = MyPriorityQueue()
queue.put('item2', 1)
queue.put('item1', 1)

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

示例输出:

item2
item1

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

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