python LRU

LRU: 最近最少使用

#!/usr/bin/env python
# encoding: utf-8
from collections import OrderedDict


class LRU(object):
    """Limit size, evicting the least recently looked-up key when full"""

    __slots__ = ['maxsize', 'cache']

    def __init__(self, maxsize=2000):
        self.maxsize = maxsize
        self.cache = OrderedDict()

    def move_to_end(self, key):
        value = self.cache.pop(key)
        self.cache[key] = value

    def __getitem__(self, key):
        value = self.cache[key]
        self.move_to_end(key)
        return value

    def __setitem__(self, key, value=None):
        if key in self.cache:
            self.move_to_end(key)
        self.cache[key] = value
        while len(self.cache) > self.maxsize:
            self.cache.popitem(last=False)

    def __str__(self):
        return self.cache.__str__()

    def __contains__(self, item):
        if item in self.cache:
            self.move_to_end(item)
            return True
        return False

    def __iter__(self):
        return self.cache.__iter__()

    def __len__(self):
        return self.cache.__len__()

    def __delitem__(self, key):
        return self.cache.__delitem__(key)

    def setdefault(self, key, value=None):
        if key not in self.cache:
            self[key] = value
            return value
        return self.cache[key]

    def clear(self):
        self.cache.clear()

    def items(self):
        return self.cache.items()

    def iteritems(self):
        return self.cache.iteritems()

    def pop(self, key):
        return self.cache.pop(key)


if __name__ == '__main__':
    cache = LRU(maxsize=3)

    cache['a'] = 1
    cache['b'] = 2
    cache['c'] = 3
    print(cache)  # OrderedDict([('a', 1), ('b', 2), ('c', 3)])

    print(cache['a'])  # 1
    print(cache)  # OrderedDict([('b', 2), ('c', 3), ('a', 1)])

    cache['e'] = 12
    print(cache)   # OrderedDict([('c', 3), ('a', 1), ('e', 12)])

    if 'c' in cache:
        print 'hit'
    print(cache)  # OrderedDict([('a', 1), ('e', 12), ('c', 3)])

    cache['z'] = 11
    print(cache)  # OrderedDict([('e', 12), ('c', 3), ('z', 11)])

参考:

 https://github.com/amitdev/lru-dict

GitHub - jlhutch/pylru: A least recently used (LRU) cache for Python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值