首页 > 解决方案 > 如何在 Heapq 中查找元素的位置

问题描述

我正在尝试使用 Python 实现 HeapQ,但我坚持这种情况,我需要在哪里获取队列中键的位置?. 我碰壁试图解决这个问题。任何提示将不胜感激。

标签: python-3.xdata-structuresheapq

解决方案


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))

推荐阅读