gpt4 book ai didi

python - 在Python中重载优先级队列的比较器

转载 作者:行者123 更新时间:2023-11-28 20:27:04 25 4
gpt4 key购买 nike

C 中的伙计们为了将节点插入优先级队列,我们​​不得不重载 < operator 。有没有类似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 上看到了一些解释,需要更多解释。谢谢。

最佳答案

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

class PQEntry:

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

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

关于python - 在Python中重载优先级队列的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10045405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com