在 Python 3 中,我像这样使用 heapq:
import heapq
heap = [3]
heapq.heapify(heap)
heapq.heappush(heap, 5)
# Push more values...
# I can iterate heap like so, but by the end it will be empty:
while (heap):
curr = heapq.heappop(heap)
# Do whatever with curr
有没有办法迭代 heapq 以便我按排序顺序获取值而不改变 heapq/丢失数据?
如果没有,我怎样才能有效地模仿所需的行为?
我想出的解决方案是创建一个临时堆,当我从原始堆弹出时推送到它,一旦我完成迭代,将原始堆设置为等于临时堆。
当然这不是很有效,并且改变了原始堆引用的对象。
temp = []
heapq.heapify(temp)
while(heap):
curr = heapq.heappop(heap)
heapq.heappush(temp, curr)
# Do whatever with curr
heap = temp