【发布时间】:2018-05-30 18:37:11
【问题描述】:
我有一些对象,每个对象都有一个唯一的 ID,这些对象被插入到各种列表中。这些对象需要经常从其对应列表的中间删除,通常是O(n),所以我想将它们的位置保存在dict 中,并在每次我想检索对象的位置在O(1) 中删除它。
class Node(object):
def __init__(self, lst_id, unique_id):
self.lst_id = lst_id
self.unique_id = unique_id
n1 = Node('a', 1)
n2 = Node('a', 2)
n3 = Node('b', 3)
node_lsts = {}
for node in [n1,n2,n3]:
if node.lst_id in node_lsts:
node_lsts[node.lst_id].append(node)
else:
node_lsts[node.lst_id] = [node]
nodes_hash = {n1.unique_id: n1, n2.unique_id: n2, n3.unique_id: n3}
ID_TO_REMOVE = 1
在上面的例子中,如果我简单地调用del nodes_hash[ID_TO_REMOVE],node_lsts 中的相应对象即使从字典中删除,它仍然存在 - 我应该如何将它从 O(1) 中的相应列表中删除?
在 C++ 中,我可以将指向邻居列表的指针保留为节点成员变量(链表),并通过其内存地址查找节点,获取指向其邻居的指针,取消该节点与其邻居的链接(从而将其从 ' list') 最后释放节点。我正在尝试复制这种行为。
【问题讨论】:
-
你经常用
nodes_lst_a做什么?随机访问?迭代?追加到列表的任一端? -
也许我错过了一些东西,为什么不使用
nodes_hash中的索引从nodes_lst_a中删除它?此外,你为什么不使用 only 哈希? -
@alfasin:
lst.pop(k)在 O(len(lst) - k) 附近,这对于随机弹出不是很好。 -
@Katie 您必须找到或创建一个链表实现才能在 Python 中实现这一点。标准库不提供这个(有
deque,但这不允许引用双端队列中的节点)。 Python 的list更像是C++ 中的std::vector<Object*> -
@Katie 是的,在数百个中,我怀疑天真的解决方案可能仍然具有竞争力。
标签: python list pointers dictionary memory