如果我在堆中推出列表元素,将使用什么堆订购属性?

发布于 2025-02-02 02:20:51 字数 316 浏览 3 评论 0原文

假设我创建一个堆,并在堆内推出一些列表元素,如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谈情不如逗狗 2025-02-09 02:20:51

我希望列表中的第一个元素用于Min Heap Ordering属性。

那将会发生。将比较您作为参数所传递的项目heappush。在Python中,将其第一个成员比较列表,如果是领带,则由其第二会员等。因此,例如[2,4,2]小于[2,8,1]。这是一种与列表和元素相关的行为,并非针对hapq,但hapq依赖于此。

在您的示例中,当您继续从堆中弹出元素时,如下:

while pq:
    print(heappop(pq))

您会以分类顺序输出:

[2, 4, 2]
[4, 0, 1]
[7, 1, 3]

备注

,因为您不希望堆上的元素被突变(因为那可能会破坏适当的堆订单),您应该更好地使用元组而不是 lists

heappush(pq, (4,0,1))
heappush(pq, (7,1,3))
heappush(pq, (2,4,2))

I want the first element of the list to be used in min heap ordering property.

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 for heapq, but heapq relies on it.

In your example, when you continue to pop the elements from the heap, like this:

while pq:
    print(heappop(pq))

You'll get them output in sorted order:

[2, 4, 2]
[4, 0, 1]
[7, 1, 3]

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:

heappush(pq, (4,0,1))
heappush(pq, (7,1,3))
heappush(pq, (2,4,2))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文