【发布时间】:2014-06-29 05:19:30
【问题描述】:
我想使用 Python 的 heapq 模块。但是,我需要跟踪每个值设置为哪个索引。
所以我写了
class heap(list):
def __init__(self,xs):
super(heap,self).__init__(xs)
self._index_table = {x:i for i,x in enumerate(self)}
def __setitem__(self,i,v):
print(i,v)
super(heap,self).__setitem__(i,v)
self._index_table[v] = i
def append(self,x):
super(heap,self).append(x)
self._index_table[x] = len(self)-1
from heapq import heapify, heappush, heappop, _siftdown, _siftup
h = heap([4,3,2,1])
heapify(h)
heappush(h,12)
print(h)
print(h._index_table)
这会打印出来
[1, 3, 2, 4, 12]
{1: 3, 2: 2, 3: 1, 4: 0}
heapify 和 heappush 修改了我列表中的条目,以规避我试图捕获所有作业的尝试。
为什么会这样?有没有解决的办法?还有一种方法可以让我使用heapq 模块并仍然跟踪每个值对应的索引吗?
编辑:
看起来我的代码有一个 heapify(h) 行,而我在原始帖子中没有。解决了这个问题。
【问题讨论】:
-
我没有具体的建议,但看起来
heapify和heappush正在调用列表修改方法,但您没有重载。您是否尝试过查找heapq模块的源代码以查看它调用了哪些列表方法? -
@SamMussmann heapq.py 看起来主要是使用简单的赋值和追加。但实际上我只是注意到它在底部导入了一个C implementation。 python 代码本身看起来应该和我的代码配合得很好......