Meg*_*dyZ 3 python heap tuples priority-queue
我正在尝试在元组列表上实现最小堆。例如:
A=[('a',2),('b',1)]
Run Code Online (Sandbox Code Playgroud)
我如何根据这些元组的第二个元素堆化 A ,以便将 A 堆化为[('b',1),('a',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
Run Code Online (Sandbox Code Playgroud)
产生:
('c', 0)
('b', 1)
('d', 1)
('a', 2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9267 次 |
| 最近记录: |