首页 > 编程语言 > 详细

Python OrderedDict使用

时间:2017-03-25 23:53:37      阅读:329      评论:0      收藏:0      [点我收藏+]

一、最近最少使用实现:

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)

  

Python OrderedDict使用

原文:http://www.cnblogs.com/styier/p/6616405.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!