python-3.x - 如何在 Heapq 中查找元素的位置
问题描述
我正在尝试使用 Python 实现 HeapQ,但我坚持这种情况,我需要在哪里获取队列中键的位置?. 我碰壁试图解决这个问题。任何提示将不胜感激。
解决方案
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))
推荐阅读
- javascript - 如何在单击按钮时使用 CSS 显示属性?
- git - 云构建步骤执行但未将功能部署到云功能?
- autoconf - `autoreconf` 如何创建 m4/ 文件夹?
- kubernetes - 为什么我在 Kubernetes 中需要 3 种不同类型的探针:startupProbe、readinessProbe、livenessProbe
- javascript - 如何将 Axios 错误返回给客户端?(不仅记录)
- python-3.x - 从列表中删除多个元素
- ios - Swift:如何为数组中的变量赋值?
- javascript - map函数在useEffect中运行后如何设置值
- c# - 除了作为访问修饰符和序列化字段之外,“公共”的统一功能是什么?
- c++ - 白色方形 SFML