2012-04-06 128 views
0

C中的伙计将节点推入优先级队列中,我们不得不重载<运算符。有没有类似于python优先队列中的东西?在Python中重载优先级队列的比较器

用C

e.g:

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上看到了一些解释,需要更多解释。谢谢。

+1

你甚至试图谷歌这个? – Marcin 2012-04-06 15:15:55

+0

这不是C,我想我问了一个有效的问题;没有必要投降我。 – 2012-04-07 01:42:00

回答

7

将数据封装在类中并覆盖__cmp__以返回您想要的比较结果。例如。

class PQEntry: 

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

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

我想你的意思是按照优先次序进行比较?否则,这个例子不会有很大意义。 – 2012-04-06 15:49:57

+0

@NiklasB。你是对的,似乎有人已经做了编辑,虽然 – 2012-04-06 16:09:27

+0

是的,那就是我;)只是想让你知道它,以防我误解了你的帖子。 – 2012-04-06 16:11:17