欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实现一个FIFO的dict

程序员文章站 2024-03-17 23:41:16
...
#!/usr/bin/env python
#_*_ coding:utf-8 _*_

__author__ = 'Noiccy'
'''description:实现一个FIFO的dict'''

from collections import OrderedDict

class LastUpdatedOrderedDict(OrderedDict):
    """docstring for LastUpdatedOrderedDict"""
    def __init__(self, capacity):
        super(LastUpdatedOrderedDict, self).__init__()
        self.__capacity = capacity

    def __setitem__(self, key, value):
        containskey = 1 if key in self else 0
        if len(self) - containskey >= self.__capacity:
            last = self.popitem(last = False)   #False:FIFO方式,True:LIFO方式
            print('remove:', last)
        if containskey:
            del self[key]
            print('set:', (key, value))
        else:
            print('add:', (key, value))
        OrderedDict.__setitem__(self, key, value) #将元素存入dict

if __name__ == '__main__':
    fifo_dict = LastUpdatedOrderedDict(3)
    fifo_dict['x'] = 1
    fifo_dict['y'] = 2
    fifo_dict['x'] = 3
    fifo_dict['z'] = 1
    fifo_dict['t'] = 0
    print(fifo_dict)

参考链接:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431953239820157155d21c494e5786fce303f3018c86000

相关标签: FIFO OrderedDict