python指定大小的字典实现,python指定字典,一段示例程序,从pyth
python指定大小的字典实现,python指定字典,一段示例程序,从pyth
一段示例程序,从python的默认dict继承,接口方法和默认的dict一模一样,单需要在构造函数中指定字典中允许的最多条目。
import timeclass SizedDict(dict): ''' Sized dictionary without timeout. ''' def __init__(self, size=1000): dict.__init__(self) self._maxsize = size self._stack = [] def __setitem__(self, name, value): if len(self._stack) >= self._maxsize: self.__delitem__(self._stack[0]) del self._stack[0] self._stack.append(name) return dict.__setitem__(self, name, value) # Recommended but not required: def get(self, name, default=None, do_set=False): try: return self.__getitem__(name) except KeyError: if default is not None: if do_set: self.__setitem__(name, default) return default else: raiseclass CacheDict(dict): ''' A sized dictionary with a timeout (seconds) ''' def __init__(self, size=1000, timeout=None): dict.__init__(self) self._maxsize = size self._stack = [] self._timeout = timeout def __setitem__(self, name, value, timeout=None): if len(self._stack) >= self._maxsize: self.__delitem__(self._stack[0]) del self._stack[0] if timeout is None: timeout = self._timeout if timeout is not None: timeout = time.time() + timeout self._stack.append(name) dict.__setitem__(self, name, (value, timeout)) def get(self, name, default=None): try: focus = self.__getitem__(name) if focus[1] is not None: if focus[1] < time.time(): self.__delitem__(name) self._stack.remove(name) raise KeyError return focus[0] except KeyError: return default#sample usage:# d = SizedDict()# for i in xrange(10000): d[i] = 'test'# print len(d)
相关内容
- python正则表达式学习代码,python正则表达式,Regexp.py''
- web.py中自定义jinja2模块,web.pyjinja2模块,web.py是一个轻量
- 用Tornado连接新浪微博,Tornado连接新浪,前几天心血来潮
- python金额小写转换代码,python金额小写,[Python]代码de
- Python 获取文件夹的大小,python获取文件夹,[Python]代码
- python四舍五入,,python的内置函数r
- python 使用MySQLdb连接mysql,pythonmysqldb,MySQLdb顾名思义,
- python处理JSON中的浮点数不精确问题,pythonjson浮点数,有
- python 缩略图,给图片加水印,,这里使用了PIL类库。[
- python比较两个文件的差异,python两个差异,下面的pytho
评论关闭