实现一个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)
下一篇: 双口FIFO与RAM