使用 heapq 对元组进行排序
我正在使用 heapq
模块来堆-对元组列表进行排序。
但是,对于第一个元组的键上的绑定,heapq 不会自动回退到下一个键:
import heapq
x = [(3, 0, 0), (6, 0, 1), (2, 1, 0), (3, 1, 1)]
heapq.heapify(x)
print(x)
将打印:
[(2, 1, 0), (3, 1, 1), (3, 0, 0), (6, 0, 1)]
我期望 (3, 0, 0)
应该出现在 (3, 1, 1)
。我需要指定自定义的比较方法吗?或者我该如何进行这项工作?
I'm using heapq
module to heap-sort a list of tuples.
However, for tie on the first tuple's key, heapq does not auto fallback to the next key:
import heapq
x = [(3, 0, 0), (6, 0, 1), (2, 1, 0), (3, 1, 1)]
heapq.heapify(x)
print(x)
Will print:
[(2, 1, 0), (3, 1, 1), (3, 0, 0), (6, 0, 1)]
I expect (3, 0, 0)
should come before (3, 1, 1)
. Do I need to specify a customized comparison method? or how do I make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如文档所述,
但这并不意味着其他元素是有序的。调用
heapify()
后,您会得到When you remove the first (smallest) item, the heap will reorder myself:
Gives
要获取完整的有序列表,请实现
heapsort()
函数如示例中所述。As the documentation states,
but that doesn't mean that the other elements are ordered. After calling
heapify()
, you getWhen you remove the first (smallest) item, the heap will reorder itself:
gives
To get the full ordered list, implement a
heapsort()
function as described in the examples.要使用
heapq
模块对元组列表进行排序,您可以实现heapsort()
函数,如 基本示例 部分:如您所见,
(3, 0, 0)
会先来(3, 1, 1)
正如预期的那样。To sort the tuples list using the
heapq
module, you could implement theheapsort()
function as shown in the Basic Examples section of the documentation:As you can see,
(3, 0, 0)
will come before(3, 1, 1)
as expected.事实证明,当您直接提取堆时,顺序与顺序弹出它们时的顺序不同。虽然当您打印它时,第二个/第三个元素没有排序,但是当您按顺序弹出它们时,它们确实已排序:
产生:
It turns out when you pring the heap directly, the order is different than the order when you pop them sequentially. Though when you print it, the second/third element is not soreted, however they are INDEED sorted when you pop them in order:
produces: