首页 > 编程语言 > 详细

python collections模块 之 orderdict

时间:2019-10-19 11:43:14      阅读:81      评论:0      收藏:0      [点我收藏+]

普通字典善于隐射,其次追踪插入顺序。而 orderdict 更善于后者。因为 orderdict 内部维护了一个双向链表,大小会是普通字典的两倍。

 

增加方法:

popitem(last=True)

  移除并返回一个键值对,last=True 时,后进先出,反之,先进先出。

move_to_end(key, last=True)

  last=True时,将键值对移至最右。反之,移至最左。key不存在时,抛错 KeyError。

 

 

应用:

记录最后一次操作的键值对:

class LastUpdatedOrderedDict(OrderedDict):
    Store items in the order the keys were last added

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        super().move_to_end(key)

限制记录大小,当记录数超出时,删除最少查找的key:

class LRU(OrderedDict):
    Limit size, evicting the least recently looked-up key when full

    def __init__(self, maxsize=128, *args, **kwds):
        self.maxsize = maxsize
        super().__init__(*args, **kwds)

    def __getitem__(self, key):
        value = super().__getitem__(key)
        self.move_to_end(key)
        return value

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        if len(self) > self.maxsize:
            oldest = next(iter(self))
            del self[oldest]

 

python collections模块 之 orderdict

原文:https://www.cnblogs.com/BeautifulWorld/p/11703145.html

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