C中的人把节点推到一个优先级队列中,我们必须重载例如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上看到了一些解释,需要更多的解释。谢谢。

最佳答案

将数据包装到一个类中并重写__cmp__以返回您希望用于比较的内容。例如。

class PQEntry:

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

    def __cmp__(self, other):
         return cmp(self.priority, other.priority)

10-07 19:07
查看更多