我正在尝试使用Python实现HeapQ,但在这种情况下我陷入了困境,在这种情况下,我需要获取密钥在队列中的位置? 。我试图解决这个问题。任何提示将不胜感激。
答案 0 :(得分:0)
Python 内置 heapq 实现了一个最小堆。因此,如果您的键是最小值,则键的索引为零。如果要查找任何其他元素的索引,只需使用列表中的 index 方法。例如,请参见下面的代码。
import heapq
numbers = [1, 11, 2, 5, 3, 9, 6]
heap = [] # a list which will be used as heap
for number in numbers:
heapq.heappush(heap, number)
# heapq is min heap. The minimum element will be at the root or index 0.
# The following line will print 1 as it is the minimum in the list.
print(heap[0])
# To find a element index just use the index function on the list
print(heap.index(11))