从堆弹出异常结果?

Jan*_*ay 1 python heap python-2.7

我有一个定义为列表列表的简单堆。我使用来自heapq模块的heapop来提取具有最小键的列表(据我所知,它隐式是内部列表的第一个元素)。但是在以下情况下,弹出操作似乎给出了异常的结果。

有人可以解释为什么吗?

堆= [[0,0,0],[inf,1,1],[inf,2,2],[5,3,3],[inf,4,4]]

heapq.heappop(堆)

[0,0,0]

heapq.heappop(堆)

[inf,1,1]

heapq.heappop(堆)

[5、3、3]

heapq.heappop(堆)

[inf,2,2]

heapq.heappop(堆)

[inf,4,4]

Dr *_*ile 5

问题是您在不是堆的列表上使用了heapq。该文档讨论了使用heapify命令,该命令确实有效:

>>> import heapq
>>> from numpy import inf
>>> heap=[[0, 0, 0], [inf, 1, 1], [inf, 2, 2], [5, 3, 3], [inf, 4, 4]]
>>> heapq.heapify(heap)
>>> heap
[[0, 0, 0], [5, 3, 3], [inf, 2, 2], [inf, 1, 1], [inf, 4, 4]]
>>> heapq.heappop(heap)
[0, 0, 0]
>>> heapq.heappop(heap)
[5, 3, 3]
>>> heapq.heappop(heap)
[inf, 1, 1]
>>> heapq.heappop(heap)
[inf, 2, 2]
>>> heapq.heappop(heap)
[inf, 4, 4]
Run Code Online (Sandbox Code Playgroud)