Skip to main content
 首页 » 编程设计

python之使用 queue.PriorityQueue,不关心比较

2025年05月04日22lovecherry

我正在尝试在 Python 3(.6) 中使用 queue.PriorityQueue。

我想存储具有给定优先级的对象。但是,如果两个对象具有相同的优先级,我不介意 PriorityQueue.get 返回任何一个。换句话说,我的对象不能以整数进行比较,允许它们比较是没有意义的,我只关心优先级。

在Python 3.7's documentation ,有一个解决方案涉及 dataclasses。我引用:

If the data elements are not comparable, the data can be wrapped in a class that ignores the data item and only compares the priority number:

from dataclasses import dataclass, field 
from typing import Any 
 
@dataclass(order=True) 
class PrioritizedItem: 
    priority: int 
    item: Any=field(compare=False) 

唉,我正在使用 Python 3.6。在 the documentation of this version of Python ,没有关于使用 PriorityQueue 作为优先级的评论,也没有理会“对象值”,这在我的情况下是不合逻辑的。

有没有比在我的自定义类上定义 __le__ 和其他比较方法更好的方法?我发现这个解决方案特别丑陋且违反直觉,但这可能就是我。

请您参考如下方法:

dataclasses 只是一种避免必须创建大量样板代码的便捷方法。

您实际上不必创建类。一个也有唯一计数器值的元组:

from itertools import count 
 
unique = count() 
 
q.put((priority, next(unique), item)) 

因此,相同优先级之间的关系被后面的整数打破;因为它始终是唯一的,所以永远不会咨询 item 值。

您还可以使用直接丰富的比较方法创建一个类,使用 @functools.total_ordering 变得更简单:

from functools import total_ordering 
 
@total_ordering 
class PrioritizedItem: 
    def __init__(self, priority, item): 
        self.priority = priority 
        self.item = item 
 
    def __eq__(self, other): 
        if not isinstance(other, __class__): 
            return NotImplemented 
        return self.priority == other.priority 
 
    def __lt__(self, other): 
        if not isinstance(other, __class__): 
            return NotImplemented 
        return self.priority < other.priority