zoukankan      html  css  js  c++  java
  • OrdereDict

    od = OrderedDict()  # 按照key进入的顺序

    od['c']='c'

    od['b']='b'

    od['e']='e'

    print(od)

    print(od.keys())

    od.move_to_end('e',last=False)  # last控制移到左端还是右端

    print(od)

    od.popitem(last=True)  # last是控制移除最左端还是最有段

    print(od)

    od.pop('e')  # 有字典的方法

    print(od)

    注意一点,在Python3下默认dict是有序的,这里的有序不是大小排序,是按照插入字典的顺序,而在Python2下则默认是无序的,想要保持有序需要使用OrderedDict

    使用OrderreDict实现LRUCache

    # 实现LRUcache ,实现一个有序的访问 

    # dict使用kv存储键值对得缓存

    # OrderreDict用来实现最近访问的key

    from collections import OrderedDict

    class  LRUCasche:

        def __init__(self,capacity = 256):

            self.od = OrderedDict()

            self.capacity = capacity

        def get(self,key):  # 访问

            if key in  self.od:

                val = self.od[key]

                self.od.move_to_end(key)  # 每次访问更新最近使用的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)  # 移除最左端的

  • 相关阅读:
    python之json&pickle
    python之装饰器
    软件测试基础
    软件测试分类
    python3文件的读写操作
    python3对excel文件读写操作
    Java集合整理
    mybatis一对多关系的关联查询
    用xftp从win7系统传输一些必要的文件到Linux
    Spring和Mybatis的整合
  • 原文地址:https://www.cnblogs.com/wenshu/p/12305892.html
Copyright © 2011-2022 走看看