python - 如何让 heapq 评估特定属性的堆?

标签 python data-structures heap

我希望拥有一堆对象,而不仅仅是数字。它们将具有堆可以排序的整数属性。在python中使用堆最简单的方法是heapq,但是在使用heapq时如何告诉它按特定属性排序呢?

最佳答案

根据 documentation 中的示例,你可以使用元组,它会按元组的第一个元素排序:

>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')

因此,如果您不想(或不能?)执行 __cmp__ 方法,您可以在推送时手动提取排序键。

请注意,如果一对元组中的第一个元素相等,则将比较后面的元素。如果这不是您想要的,您需要确保每个第一个元素都是唯一的。

关于python - 如何让 heapq 评估特定属性的堆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3954530/

相关文章:

python - Celery:组中的一个子任务总是超时

python - 在 Python 中使用 "Lookups"的 Twilio 附加组件的正确方法

c++ - 未知的C++错误: Fatal error: glibc detected an invalid stdio handle

algorithm - 包含所有对象的最小区间

python - 在python的嵌套列表中将每个元素从字符串转换为int

python - 克服 Active Directory 的 1000 条记录限制

python - 如何使用 OpenCV 覆盖图像和文本/形状?

python - 确定数字列表是否按堆顺序,Python 3.2

go - 如何在 Go 中嵌入和覆盖结构

python - 为调度程序使用堆