在python中,如何在元组列表上实现最小堆?

时间:2018-08-26 03:40:51

标签: python tuples heap priority-queue

我正在尝试在元组列表上实现最小堆。 例如:

A=[('a',2),('b',1)]

如何基于这些元组的第二个元素对A进行堆放,以便将A堆放到[('b',1),('a',2)]上? (我必须保持一个最小的堆。)

2 个答案:

答案 0 :(得分:2)

根据@JimMischel的评论,将您的元组放在优先级为第一个元素的元组中。然后使用heapq

import heapq

list = [('a', 2), ('b', 1), ('c', 0), ('d', 1)]
heap_elts = [(item[1], item) for item in list]
heapq.heapify(heap_elts)  # you specifically asked about heapify, here it is!
while len(heap_elts) > 0:
    print(heapq.heappop(heap_elts)[1])    # element 1 is the original tuple

产生:

('c', 0)
('b', 1)
('d', 1)
('a', 2)

答案 1 :(得分:0)

import heapq

A=[('a',2),('b',1), ('d', 0), ('c', 2), ('a', 2)]
h = []
for el in A:
    heapq.heappush(h, (el[1], el[0]))

print(h)

结果:

[(0, 'd'), (2, 'a'), (1, 'b'), (2, 'c'), (2, 'a')]