這裏是一個定製的OrderedDict這使N個最大鍵爲您提供:
from collections import OrderedDict
from operator import itemgetter
class LimitedSizeOrderedDict(OrderedDict):
def __init__(self, *args, **kwds):
self.maxlen = kwds.pop("maxlen", None)
if args:
try:
top_n = sorted(*args, key=itemgetter(0, 0))[-self.maxlen:]
self.min_key = top_n[0][0]
except TypeError:
raise Exception("keys should be in tuple format")
else:
self.min_key = (float("inf"), 0)
super(LimitedSizeOrderedDict, self).__init__(top_n, **kwds)
def __setitem__(self, key, value):
if self._check_size():
OrderedDict.__setitem__(self, key, value)
if key[0] < self.min_key[0]:
self.min_key = key
elif key[0] > self.min_key[0]:
self.pop(self.min_key)
OrderedDict.__setitem__(self, key, value)
self.min_key = min(self, key=itemgetter(0))
def _check_size(self):
if self.maxlen is not None:
if len(self) < self.maxlen:
return True
return False
return True
演示:
In [2]: a = LimitedSizeOrderedDict([((7,2),3), ((2, 5), 3), ((6, 0), 1)], maxlen= 2)
In [3]: a
Out[3]: LimitedSizeOrderedDict([((6, 0), 1), ((7, 2), 3)])
In [4]: a[(12, 5)] = 10
In [5]: a
Out[5]: LimitedSizeOrderedDict([((7, 2), 3), ((12, 5), 10)])
In [6]: a[(10, 5)] = 9
In [7]: a
Out[7]: LimitedSizeOrderedDict([((12, 5), 10), ((10, 5), 9)])
In [8]: a[(0, 5)] = 9
In [9]: a
Out[9]: LimitedSizeOrderedDict([((12, 5), 10), ((10, 5), 9)])
如何創建這本詞典沒有?你想在創建時或創建字典之後做到這一點? – Kasramvd
如果你不反對使用numpy它有'partition'和'argpartition',它可以在O(n)中找到頂部或底部的k。 –
對不起,我應該解釋一下,我無法將我的字典保存在內存中。 – Black