使用queue.PriorityQueue,不关心比较 [英] Using queue.PriorityQueue, not caring about comparisons
问题描述
我正在尝试在Python 3(.6)中使用queue.PriorityQueue
.
I'm trying to use queue.PriorityQueue
in Python 3(.6).
我想存储具有给定优先级的对象.但是,如果两个对象具有相同的优先级,则我不介意PriorityQueue.get
返回任何一个.换句话说,我的对象不能以整数进行比较,允许它们成为整数没有意义,我只是在乎优先级.
I would like to store objects with a given priority. But if two objects have the same priority, I don't mind PriorityQueue.get
to return either. In other words, my objects can't be compared at integers, it won't make sense to allow them to be, I just care about the priority.
在 Python 3.7的文档中,有一个涉及
In Python 3.7's documentation, there's a solution involving dataclasses
. And I quote:
如果数据元素不具有可比性,则可以将数据包装在忽略数据项并且仅比较优先级数字的类中:
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)
A,我正在使用Python 3.6.在此版本的Python文档中,对于使用
Alas, I'm using Python 3.6. In the documentation of this version of Python, there's no comment on using PriorityQueue
for the priorities, not bothering about the "object value" which wouldn't be logical in my case.
是否有比在自定义类上定义__le__
和其他比较方法更好的方法?我发现此解决方案特别丑陋且违反直觉,但这可能就是我.
Is there a better way than to define __le__
and other comparison methods on my custom class? I find this solution particularly ugly and counter-intuitive, but that might be me.
推荐答案
dataclasses
只是避免创建大量样板代码的便捷方法.
dataclasses
is just a convenience method to avoid having to create a lot of boilerplate code.
您实际上并没有拥有来创建一个类.具有唯一计数器值的元组也是如此:
You don't actually have to create a class. A tuple with a unique counter value too:
from itertools import count
unique = count()
q.put((priority, next(unique), item))
,以使相等优先级之间的联系被后面的整数打破;因为它始终是唯一的,所以永远不会查询item
值.
so that ties between equal priority are broken by the integer that follows; because it is always unique the item
value is never consulted.
You can also create a class using straight-up rich comparison methods, made simpler with @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
这篇关于使用queue.PriorityQueue,不关心比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!