import collections class LRUDict(object): ‘‘‘ 最近最少使用队列实现,最近使用的键值放后面 ‘‘‘ def __init__(self,dict_list,size): self.ordered_dict = collections.OrderedDict(dict_list) self.size = size def get(self,key): if key in self.ordered_dict: value = self.ordered_dict.get(key) self.ordered_dict.move_to_end(key) else: value = None return value def set(self,key,value): if len(self.ordered_dict) >= 10: self.ordered_dict.popitem(last=False) self.ordered_dict.update([(key,value)]) self.ordered_dict.move_to_end(key) instance = LRUDict(dict_list=[(1,1),(2,2),(3,3)],size=4) print(instance.get(1),instance.ordered_dict) instance.set(4,4) print(instance.ordered_dict) instance.set(3,9) print(instance.ordered_dict)
OR:
class LRUDict(collections.OrderedDict): def __init__(self, size, *args, **kwargs): self.size = size super(LRUDict, self).__init__(*args, **kwargs) def __getitem__(self, key): if key in self: self.move_to_end(key) return super(LRUDict, self).__getitem__(key) def __setitem__(self, key, value): if len(self) >= 10: self.popitem(last=False) super(LRUDict, self).__setitem__(key, value) self.move_to_end(key) instance = LRUDict(4, [(1, 1), (2, 2), (3, 3)]) print(instance[1], instance) instance.update([(4, 4)]) print(instance) instance.update([(3, 9)]) print(instance)
原文:http://www.cnblogs.com/styier/p/6616405.html