gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:56:03 26 4
gpt4 key购买 nike

我希望拥有一堆对象,而不仅仅是数字。它们将具有堆可以排序的整数属性。在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/

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