<p>如果你打算用一个Python进程留在内存中,那么你将不得不放弃<code>dict</code>数据类型,正如你所说的,它有很好的运行时性能特性,但它使用大量内存来实现这一点。在</p>
<p>真的,我认为@msw的评论和@Udi的回答都恰到好处,你应该看看磁盘上的或者至少是某种进程外存储,也许RDBMS是最容易实现的。在</p>
<p>但是,如果您确定需要保留在内存中并处于进程中,我建议使用已排序的列表来存储数据集。您可以在O(logn)时间内进行查找,在恒定时间内执行插入和删除,并且您可以自己打包代码,这样使用情况看起来非常像<code>defaultdict</code>。这样做可能会有所帮助(除了底部的测试之外,不会进行调试):</p>
<pre><code>import bisect
class mystore:
def __init__(self, constructor):
self.store = []
self.constructor = constructor
self.empty = constructor()
def __getitem__(self, key):
i, k = self.lookup(key)
if k == key:
return v
# key not present, create a new item for this key.
value = self.constructor()
self.store.insert(i, (key, value))
return value
def __setitem__(self, key, value):
i, k = self.lookup(key)
if k == key:
self.store[i] = (key, value)
else:
self.store.insert(i, (key, value))
def lookup(self, key):
i = bisect.bisect(self.store, (key, self.empty))
if 0 <= i < len(self.store):
return i, self.store[i][0]
return i, None
if __name__ == '__main__':
s = mystore(set)
s['a'] = set(['1'])
print(s.store)
s['b']
print(s.store)
s['a'] = set(['2'])
print(s.store)
</code></pre>