collections中的OrderedDict
来源:互联网 发布:sap数据导入 编辑:程序博客网 时间:2024/06/14 06:44
使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。而如果要保持Key的顺序,可以用OrderedDict
注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:
OrderedDict可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key:
class LastUpdatedOrderedDict(OrderedDict): def __init__(self, capacity): super().__init__() #super(LastUpdatedOrderedDict, self).__init__() self._capacity = capacity def __setitem__(self, key, value): containsKey = 1 if key in self else 0 print('self1:',self) print('len(self):',len(self)) # 如果dict容量已满 if len(self) - containsKey >= self._capacity: print('%s(len) - %s(containsKey)>= %s(self._capacity):' % (len(self),containsKey,self._capacity)) # 则删除最先添加的key last = self.popitem(last=False) print('remove:', last) print('self2:',self) # 检查dict里是否已经存在要增加的(key,value)中的key if containsKey: # 删除原来的key del self[key] print('set:', (key, value)) print('self3:',self) # 如果dict中没有要添加的key else: print('add:', (key, value)) print('self4:',self) OrderedDict.__setitem__(self, key, value) print('self5:',self)dic=LastUpdatedOrderedDict(2)dic['a']=1print('.......')dic['b']=2print('.......')dic['c']=3print('.......')dic['b']=6
结果:
........................................self1: LastUpdatedOrderedDict()len(self): 0add: ('a', 1)self6: LastUpdatedOrderedDict()self7: LastUpdatedOrderedDict([('a', 1)]).......self1: LastUpdatedOrderedDict([('a', 1)])len(self): 1add: ('b', 2)self6: LastUpdatedOrderedDict([('a', 1)])self7: LastUpdatedOrderedDict([('a', 1), ('b', 2)]).......self1: LastUpdatedOrderedDict([('a', 1), ('b', 2)])len(self): 22(len) - 0(containsKey)>= 2(self._capacity):remove: ('a', 1)self3: LastUpdatedOrderedDict([('b', 2)])add: ('c', 3)self6: LastUpdatedOrderedDict([('b', 2)])self7: LastUpdatedOrderedDict([('b', 2), ('c', 3)]).......self1: LastUpdatedOrderedDict([('b', 2), ('c', 3)])len(self): 2set: ('b', 6)self5: LastUpdatedOrderedDict([('c', 3)])self7: LastUpdatedOrderedDict([('c', 3), ('b', 6)])........................................
从运行结果可以理清思路
阅读全文
2 0
- collections中的OrderedDict
- collections OrderedDict
- Python的collections模块中的OrderedDict有序字典
- Python collections OrderedDict
- hackerrank Collections.OrderedDict()
- python中的有序字典OrderedDict
- python 2-6 如何让字典保持有序collections.OrderedDict
- Python HackerRank|Word Order(OrderedCounter)(from collections import Counter, OrderedDict)
- python中排序,函数sort、sorted、argsort,collections.OrderedDict类
- Python文件操作,时间日期操作,collections增强,Deque(类似java的LinkedList),OrderedDict,Counter
- python OrderedDict
- Python OrderedDict
- System.Collections中的内容
- Java中的Collections
- Collections中的静态方法
- java中的Collections类
- Python中的collections模块
- Python中的collections
- Sad / zeroModalAPI
- maven本地安装jar包之后,编译报错找不到jar包
- Hibernate学习笔记 -- day04 标识符、主键生成策略
- C语言 输出宽度
- 第一篇 ENVI中自定义坐标系文件拒绝访问的解决方法
- collections中的OrderedDict
- ASIHTTPRequest 使用详解
- MySql 入门(2)
- dreamweaver中用正则表达式查找替换批量删除 tppabs标签的方法 一步到位
- 观《逻辑思维 -- 时间的朋友》跨年演讲
- 折半查找的改进
- kaoshi(Utils读取)
- Python3.6安装MySQL
- Android 使用MediaPlayer播放音频