zoukankan      html  css  js  c++  java
  • Python OrderedDict使用

    一、最近最少使用实现:

    import collections
    class LRUDict(object):
        '''
        最近最少使用队列实现,最近使用的键值放后面
        '''
        def __init__(self,dict_list,size):
            self.ordered_dict = collections.OrderedDict(dict_list)
            self.size = size
    
        def get(self,key):
            if key in self.ordered_dict:
                value = self.ordered_dict.get(key)
                self.ordered_dict.move_to_end(key)
            else:
                value = None
            return value
    
        def set(self,key,value):
            if len(self.ordered_dict) >= 10:
                self.ordered_dict.popitem(last=False)
            self.ordered_dict.update([(key,value)])
            self.ordered_dict.move_to_end(key)
    
    instance = LRUDict(dict_list=[(1,1),(2,2),(3,3)],size=4)
    print(instance.get(1),instance.ordered_dict)
    instance.set(4,4)
    print(instance.ordered_dict)
    instance.set(3,9)
    print(instance.ordered_dict)
    

    OR:

    class LRUDict(collections.OrderedDict):
        def __init__(self, size, *args, **kwargs):
            self.size = size
            super(LRUDict, self).__init__(*args, **kwargs)
    
        def __getitem__(self, key):
            if key in self:
                self.move_to_end(key)
            return super(LRUDict, self).__getitem__(key)
    
        def __setitem__(self, key, value):
            if len(self) >= 10:
                self.popitem(last=False)
            super(LRUDict, self).__setitem__(key, value)
            self.move_to_end(key)
    
    
    instance = LRUDict(4, [(1, 1), (2, 2), (3, 3)])
    print(instance[1], instance)
    instance.update([(4, 4)])
    print(instance)
    instance.update([(3, 9)])
    print(instance)
    

      

    有志者,事竟成!
  • 相关阅读:
    vue 使用sass 和less
    生命周期函数以及vue的全局注册
    vue-router的简单实现原理
    vue的三种传参方式
    配置router列表
    vue传参二
    Gym 101933E(状态压缩+记忆化搜索)
    Gym 101933 A(dp)
    Gym 101775H(dp)
    Gym 101775 D (思维)
  • 原文地址:https://www.cnblogs.com/styier/p/6616405.html
Copyright © 2011-2022 走看看