LRUcache的实现
https://juejin.im/post/5a9e6835f265da23937697ea-简单通俗容易理解
http://www.importnew.com/18758.html
https://blog.csdn.net/hxqneuq2012/article/details/52709652
LRUcache实现的python代码:
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.queue = collections.OrderedDict()
def get(self, key):
if key not in self.queue:
return -1 // 要找的数据不在缓存中返回-1
value = self.queue.pop(key) // 将命中缓存的数据移除
self.queue[key] = value // 将命中缓存的数据重新添加到头部
return self.queue[key]
def put(self, key, value):
if key in self.queue: // 如果已经在缓存中,则先移除老的数据
self.queue.pop(key)
elif len(self.queue.items()) == self.capacity:
self.queue.popitem(last=False) // 如果不在缓存中并且到达最大容量,则把最后的数据淘汰
self.queue[key] = value // 将新数据添加到头部
作者:simpleapples
链接:https://juejin.im/post/5a9e6835f265da23937697ea
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
备注:
1.collections.OrderedDict()是指python中的有序的字典。按照输入的顺序保存的结果。
2.popitem(last=False)如果last=true就按照LIFO的顺序弹出元素。如果last=false就按照FIFO的顺序弹出元素。