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)  # 移除最左端的

  • 相关阅读:
    JDBC 复习4 批量执行SQL
    JDBC 复习3 存取Oracle大数据 clob blob
    Oracle复习
    Linux命令(1)grep
    JDBC 复习2 存取mysql 大数据
    JDBC 复习1 DBUtil
    php 环境搭建问题
    Windows 批处理 bat 开启 WiFi 菜单选项 设置ID PWD
    Bat 批处理启动和停止Oracle 服务
    docker 学习1 WSL docker ,Windows docker
  • 原文地址:https://www.cnblogs.com/wenshu/p/12305892.html
Copyright © 2011-2022 走看看