python - 类型错误 : '<' not supported between instances of 'State' and 'State' PYTHON 3

标签 python python-3.x priority-queue

我正在尝试使用队列类中的 PriorityQueue。但是,我在将自定义对象放入我的 PQ 时遇到了问题。我已经实现了 __cmp__功能如下:

def __cmp__(self, other):
    return (self.priority > other.priority) - (self.priority < other.priority)

我希望 PriorityQueue 按优先级字段排序,如我的 init 函数中分配的那样:

def __init__(self, board, priority=0):
    self.priority = priority
    # Other logic

但是,当我运行将 State 对象插入 PQ 的代码时,出现此错误:TypeError: '<' not supported between instances of 'State' and 'State'

这是运行 PQ 的代码。

if op.precond(S):
            new_state = op.state_transf(S)
            if not (OPEN.queue.__contains__(new_state)) and not (new_state in CLOSED):
                GVALUES[Problem.hash(new_state)] = get_distance_value(op, new_state)
                HEUR_VALUES[Problem.hash(new_state)] = get_AStar_value(new_state)
                print("NEW STATE: " + str(new_state))
                OPEN.put(new_state)
                print("OPEN: " + str(OPEN.queue))

其中 OPEN 是 priorityQueue。

任何帮助将不胜感激...因为将值插入 PQ 应该非常简单。

最佳答案

在 Python 3 中,您需要定义 __lt____eq__ 而不是 __cmp__

参见 https://docs.python.org/3.1/library/stdtypes.html#comparisons .

关于python - 类型错误 : '<' not supported between instances of 'State' and 'State' PYTHON 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43481158/

相关文章:

python - 在 PyQt 中将图像添加到 QTableWidget

python-3.x - python3.6,async with和await的区别

python - 如何在 python 3 中使用带有并发 future ThreadPoolExecutor 的队列?

c++ - 设置priority_queue容器的好处

c++ - 使用优先级队列结构?

C++ priority_queue 没有推送?

python - 附加到元组列表

c# - 使用 PTVS 进行 IronPython 远程调试

python - 计算从条件标记的子集行到标记行下方的其余行的变化率

python - 为什么我不能在 Python 3 中使用 `print __doc__`?