2

C 语言中的人要将节点推入优先级队列,我们​​必须重载 < 运算符。python优先级队列中是否有类似的东西。

例如在 C 中:

    struct node
    {

    int city , weight

    }

    bool operator < (node a, node b)
    {
     return a.weight > b.weight;
    }

    int main()
   {
     node a,b,c;
     priority_queue <node> pq;
     pq.push(a);pq.push(b);pq.push(c);
     return 0;
   }

是否有任何类似的方法可以在 Python 中定义优先级队列;如果需要帮助,我无法在 python.org 文档的头部或尾部获取优先级队列。我在 stackoverflow 上看到了一些解释,需要更多解释。谢谢。

4

1 回答 1

8

将数据包装在一个类中并覆盖__cmp__以返回您想要进行比较的内容。例如

class PQEntry:

    def __init__(self, priority, value):
        self.priority = priority
        self.value = value

    def __cmp__(self, other):
         return cmp(self.priority, other.priority)
于 2012-04-06T15:23:46.287 回答