标签:
OrderedDict
可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key:
#!/usr/bin/env python #-*- coding: utf8 -*- from collections import OrderedDict class LastUpdatedOrderedDict(OrderedDict): def __init__(self, capacity): #super(LastUpdatedOrderedDict, self).__init__() OrderedDict.__init__(self)#注意这里有self 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(False) print ‘remove:‘, last if containsKey: del self[key] print ‘set:‘, (key, value) else: print ‘add:‘, (key, value) super(LastUpdatedOrderedDict, self).__setitem__(key, value) #OrderedDict.__setitem__(self, key, value) FIFO = LastUpdatedOrderedDict(5) FIFO.__setitem__(‘huangyi‘, ‘lz‘) FIFO.__setitem__(1, 1) FIFO.__setitem__(2, 2) FIFO.__setitem__(3, 3) FIFO.__setitem__(4, 4)
super(LastUpdatedOrderedDict, self).__init__()等价于OrderedDict.__init__(self),super返回LastUpdatedOrderedDict的父类OrderedDict。注意前面参数不带self,后面参数带self。
last = self.popitem(False)的popitem不带参数(或带True)时返回最后一个元素,带参数False时返回第一个元素。
References
[1].https://docs.python.org/3/library/stdtypes.html?highlight=popitem#dict.popitem
[2].http://www.cnblogs.com/lovemo1314/archive/2011/05/03/2035005.html
标签:
原文地址:http://my.oschina.net/lvyi/blog/383454