python中堆元素的比较顺序

use*_*474 2 python sorting algorithm heap python-3.x

我正在使用堆来使用 heapq 制作优先级队列。

我使用将一个项目插入队列

heapq.heappush(h, (cost, node))

其中h是堆对象,cost是我对堆进行排序的项目,node是自定义定义类的对象。

当我运行代码时,当我h用相同的值插入两个不同的项目时,出现以下错误cost

类型错误:不可排序的类型:SearchNode() < SearchNode()

SearchNode()的类在哪里node

该错误清楚地表明 Python 正在比较第二项。

堆元素有比较顺序吗?如果是,我如何解决算法中的关系,使其不会开始比较第二项。我想到的一种可能的解决方案是重载比较运算符SearchNode()

我对 python 很陌生,所以如果我遗漏了一些非常明显的东西,请随时指出。

Leo*_*eon 5

引入一个不包含比较节点的小类:

class CostAndNode:
    def __init__(self, cost, node):
        self.cost = cost
        self.node = node

    # do not compare nodes
    def __lt__(self, other):
        return self.cost < other.cost

h = []

heapq.heappush(h, CostAndNode(1, node1))
heapq.heappush(h, CostAndNode(1, node2))
Run Code Online (Sandbox Code Playgroud)