如果我在堆中推出列表元素,将使用什么堆订购属性?
假设我创建一个堆,并在堆内推出一些列表元素,如下所示:
from heapq import heapify,heappop,heappush
pq = []
heapify(pq)
heappush(pq,[4,0,1])
heappush(pq,[7,1,3])
heappush(pq,[2,4,2])
heappop()
操作返回值将如何? 就我而言,我希望列表中的第一个元素在Min Heap Ordering属性中使用。我该如何实现?
Suppose I create a heap and push some list elements inside the heap as follows:
from heapq import heapify,heappop,heappush
pq = []
heapify(pq)
heappush(pq,[4,0,1])
heappush(pq,[7,1,3])
heappush(pq,[2,4,2])
How will the heappop()
operation return values?
In my case, I want the first element of the list to be used in min heap ordering property. How can I achieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那将会发生。将比较您作为参数所传递的项目
heappush
。在Python中,将其第一个成员比较列表,如果是领带,则由其第二会员等。因此,例如[2,4,2]
小于[2,8,1]
。这是一种与列表和元素相关的行为,并非针对hapq
,但hapq
依赖于此。在您的示例中,当您继续从堆中弹出元素时,如下:
您会以分类顺序输出:
备注
,因为您不希望堆上的元素被突变(因为那可能会破坏适当的堆订单),您应该更好地使用元组而不是 lists :
That is what will happen. The items you pass as argument in
heappush
will be compared. In Python, lists are compared by their first member, and if that is a tie, by their second member, ...etc. So for example[2,4,2]
is less than[2,8,1]
. This is a behaviour that is tied to lists and tuples, and is not specific forheapq
, butheapq
relies on it.In your example, when you continue to pop the elements from the heap, like this:
You'll get them output in sorted order:
Remark
As you don't want elements on the heap to be mutated (as that could break there proper heap order), you should better use tuples and not lists: