简体   繁体   English

使用 heapq 对元组进行排序

[英]Sorting tuples with heapq

I'm using heapq module to heap-sort a list of tuples.我正在使用heapq模块对元组列表进行堆排序。

However, for tie on the first tuple's key, heapq does not auto fallback to the next key:但是,对于第一个元组的键,heapq 不会自动回退到下一个键:

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) .我希望(3, 0, 0)应该出现在(3, 1, 1)之前。 Do I need to specify a customized comparison method?我需要指定自定义的比较方法吗? or how do I make this work?或者我如何使这项工作?

As the documentation states,正如文档所述,

its smallest element is always the root, heap[0]它的最小元素总是根,heap[0]

but that doesn't mean that the other elements are ordered.但这并不意味着其他元素是有序的。 After calling heapify() , you get调用heapify()后,您会得到

[(2, 1, 0), (3, 1, 1), (3, 0, 0), (6, 0, 1)]

When you remove the first (smallest) item, the heap will reorder itself:当您删除第一个(最小的)项目时,堆将自行重新排序:

heapq.heappop(x) # returns (2, 1, 0)
print(x)

gives

[(3, 0, 0), (3, 1, 1), (6, 0, 1)]

To get the full ordered list, implement a heapsort() function as described in the examples .要获得完整的有序列表,请按照示例中的说明实施heapsort() function。

To sort the tuples list using the heapq module, you could implement the heapsort() function as shown in the Basic Examples section of the documentation:要使用heapq模块对元组列表进行排序,您可以实现heapsort() function,如文档的基本示例部分所示:

from heapq import heappop, heappush

def heapsort(iterable):
    h = []
    for value in iterable:
        heappush(h, value)
    return [heappop(h) for i in range(len(h))]

x = [(3, 0, 0), (6, 0, 1), (2, 1, 0), (3, 1, 1)]

res = heapsort(x)
print(res)  # -> [(2, 1, 0), (3, 0, 0), (3, 1, 1), (6, 0, 1)]

As you can see, (3, 0, 0) will come before (3, 1, 1) as expected.如您所见, (3, 0, 0)将按预期出现在(3, 1, 1)之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM