python内嵌不常用数据结构以及利用OrderedDict实现LRUcache

import collections

"""
#命名tuple
#定义一个point对象,让nametuple可读
point = collections.namedtuple('ppp','x,y')
p = point(1,2)
print(p.x,p.y)

"""

"""
#双端队列
queue = collections.deque()
queue.append(1)
queue.append(2)
queue.appendleft(0)#左加
print(queue)
queue.pop()#右边出
queue.popleft()#左边出

"""

"""
#计数器
c = collections.Counter('fgdgdfghradas')
print(c)#Counter({'d': 3, 'g': 3, 'a': 2, 'f': 2, 'h': 1, 's': 1, 'r': 1})
print(c['a'])#2
c.most_common()#以列表包含元组的形式,从大到小获取计数
"""


"""

#记住字典中key插入的顺序
od = collections.OrderedDict()
od['c']= 1
od['b']= 2
od['a']= 3

print(list(od.keys()))
"""


#带有默认值的字典,没能实现
dd= collections.defaultdict()

在这里插入图片描述在这里插入图片描述
**利用python内嵌的双端队列来实现LRUcache
**

from collections import OrderedDict

class LRUCache:
    def __init__(self,capacity=128):
        self.od = OrderedDict()
        self.capacity = capacity

    def get(self,key):#每次更新最新使用的key,将他放在最右边
        if key in self.od:
            val = self.od[key]
            self.od.move_to_end(key)
            return val
        else:
            return -1
    def put(self,key,value):#更新k/v
        if key in self.od:
            del self.od[key]
            self.od[key] = value
        else:
            self.od[key] = value
            if len(self.od) > self.capacity:
                self.od.popitem(last=False)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值