Python系列之Collections内置模块(2)
来源:互联网 发布:js删除object指定元素 编辑:程序博客网 时间:2024/06/05 07:35
defaultdict 返回一个类 dict 的对象,defaultdict 是内置的 dict 类的子类。
如果访问 dict 未初始化的 key 值时,会抛出 KeyError 异常。
1 s_tuple = ('a', 'b', 'a', 'a',2 'c', 'a', 'b', 'a')3 4 c_dict = {}5 6 for s in s_tuple:7 c_dict[s] += 18 9 print(c_dict)
输出如下:
1 Traceback (most recent call last):2 File "FileNamePath", line 7, in <module>3 c_dict[s] += 14 KeyError: 'a'
对代码进行修正后如下:
1 s_tuple = ('a', 'b', 'a', 'a', 2 'c', 'a', 'b', 'a') 3 4 c_dict = {} 5 6 for s in s_tuple: 7 if s not in c_dict: 8 c_dict[s] = 1 9 else:10 c_dict[s] += 111 12 print(c_dict)
能够正常输出每个 str 出现的统计次数,不过每次循环都要进行判断当前 dict 中是否存在这个 key 值。不过 dict 的 api 中提供了 setdefault() 方法,该方法需提供两个参数,第一个为 key 值,第二个为该 key 初始状态下的默认值。如果字典中不存在此 key 值,则该方法返回默认值,反之返回该 key 值对应的 value。
1 s_tuple = ('a', 'b', 'a', 'a',2 'c', 'a', 'b', 'a')3 4 c_dict = {}5 6 for s in s_tuple:7 c_dict[s] = c_dict.setdefault(s, 0) + 18 9 print(c_dict)
下面引入 defaultdict 的用法,defaultdict 类初始化时接收一个类型作为参数,当访问的 key 值不存在时,可实例化传入的类型参数的实例作为默认值。
1 from collections import defaultdict2 3 d_defaultdict = defaultdict(list)4 5 print(d_defaultdict)6 print(d_defaultdict.__getitem__('1'))7 print(d_defaultdict)
输出如下:
1 defaultdict(<class 'list'>, {})2 []3 defaultdict(<class 'list'>, {'1': []})
由于初始化 defaultdict 时,传入的类型是 list,因此 key 为 '1' 的 value 默认为 [],如果参数为 tuple,那么 value 的默认值为 ()。
需要注意的是,默认值只有通过 defaultdict[key] 或 defaultdict.__getitem__(key) 访问 defaultdict 时才会被初始化。
extend
问题来了 defaultdict 是如何实现为不存在的 key 值初始化默认值的?
阅读 _collections.py 源码中的 class defaultdict(dict) 部分,可以看到一个 def __missing__(self, key) 的实例方法。
源码如下:
1 def __missing__(self, key): # real signature unknown; restored from __doc__2 """3 __missing__(key) # Called by __getitem__ for missing key; pseudo-code:4 if self.default_factory is None: raise KeyError((key,))5 self[key] = value = self.default_factory()6 return value7 """8 pass
由此可见,当通过 __getitem__ 方法访问 defaultdict 中的某个不存在的 key 值时,会在抛出的 KeyError 异常中进行处理,根据传入的类型参数返回初始化的 value 值。
那么,这个 __missing__ 方法中的内容可否自己实现呢,不妨试试:
1 class defaultdict_copy(dict): 2 def __missing__(self, key): 3 self[key] = 'default' 4 return 'default' 5 6 7 d_defaultdict_copy = defaultdict_copy() 8 print(d_defaultdict_copy) 9 print(d_defaultdict_copy['1'])10 print(d_defaultdict_copy)
输出如下:
1 {}2 default3 {'1': 'default'}
很明显,对于 dict 的继承类中,存在一个 __missing__ 的实例方法,可以通过重写该方法实现访问不存在的 key 值时进行 value 的初始化。
- Python系列之Collections内置模块(2)
- Python系列之Collections内置模块(2)
- Python之collections模块
- python学习系列---collections模块
- Python系列之 - Collections系列
- [转载]Python模块之Collections
- python 内置模块2
- python模块学习(collections模块)
- python高级数据结构之collections模块
- python模块系列之
- python模块系列之
- python模块系列之
- python模块系列之
- python内置模块(import)
- python内置模块(json)
- python collections模块
- Python collections模块
- Python模块: collections
- Android上常见度量单位【xdpi、hdpi、mdpi、ldpi】解读
- DBC(7):C3P0等连接池
- leetcode [Longest Common Prefix]
- java中的 clone方法
- 内存抖动,以及观测内存的状态的工具分析
- Python系列之Collections内置模块(2)
- 如何正确关闭游戏服务器
- web前端18
- R语言中将hello打印10次的两种方法
- Android Camera搭配SurfaceView开发相机基础
- 学习C++的优势
- eclipse入门使用手册
- makefile编译问题记录
- 微信开发之公众平台开发模式下的数据交互模式