collections模块
这个模块实现了特定目标的容器,以提供Python标准内建容器 dict、list、set、tuple 的替代选择。
- Counter:字典的子类,提供了可哈希对象的计数功能
- defaultdict:字典的子类,提供了一个工厂函数,为字典查询提供了默认值
- OrderedDict:字典的子类,保留了他们被添加的顺序
- namedtuple:创建命名元组子类的工厂函数
- deque:类似列表容器,实现了在两端快速添加(append)和弹出(pop)
- ChainMap:类似字典的容器类,将多个映射集合到一个视图里面
Counter
Counter是一个dict子类,主要是用来对你访问的对象的频率进行计数。
>>> import collections >>> # 统计字符出现的次数 ... collections.Counter('hello world') Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}) >>> # 统计单词个数 ... collections.Counter('hello world hello lucy'.split()) Counter({'hello': 2, 'world': 1, 'lucy': 1})
常用方法:
- elements():返回一个迭代器,每个元素重复计算的个数,如果一个元素的计数小于1,就会被忽略
- most_common([n]):返回一个列表,提供n个访问频率最高的元素和计数
- subtract([iterable-or-mapping]):从迭代对象中减去元素,输入输出可以是0或者负数
- update([iterable-or-mapping]):从迭代对象计数元素或者从另一个 映射对象 (或计数器) 添加
>>> c = collections.Counter('hello world hello lucy'.split()) >>> c Counter({'hello': 2, 'world': 1, 'lucy': 1}) >>> # 获取指定对象的访问次数,也可以使用get方法 ... c['hello'] 2 >>> # 查看元素 ... list(c.elements()) ['hello', 'hello', 'world', 'lucy'] >>> c1 = collections.Counter('hello world'.split()) >>> c2 = collections.Counter('hello lucy'.split()) >>> c1 Counter({'hello': 1, 'world': 1}) >>> c2 Counter({'hello': 1, 'lucy': 1}) >>> # 追加对象,+或者c1.update(c2) ... c1+c2 Counter({'hello': 2, 'world': 1, 'lucy': 1}) >>> # 减少对象,-或者c1.subtract(c2) ... c1-c2 Counter({'world': 1}) >>> # 清除 ... c.clear() >>> c Counter()
defaultdict
返回一个新的类似字典的对象。 defaultdict 是内置 dict 类的子类。
class collections.defaultdict([default_factory[, ...]]) >>> d = collections.defaultdict() >>> d defaultdict(None, {}) >>> e = collections.defaultdict(str) >>> e defaultdict(<class 'str'>, {})
例子
defaultdict的一个典型用法是使用其中一种内置类型(如str、int、list或dict等)作为默认工厂,这些内置类型在没有参数调用时返回空类型。
>>> e = collections.defaultdict(str) >>> e defaultdict(<class 'str'>, {}) >>> e['hello'] '' >>> e defaultdict(<class 'str'>, {'hello': ''}) >>> # 普通字典调用不存在的键时,报错 ... e1 = {} >>> e1['hello'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'hello'
使用 int 作为 default_factory
>>> fruit = collections.defaultdict(int) >>> fruit['apple'] = 2 >>> fruit defaultdict(<class 'int'>, {'apple': 2}) >>> fruit['banana'] # 没有对象时,返回0 0 >>> fruit defaultdict(<class 'int'>, {'apple': 2, 'banana': 0})
使用 list 作为 default_factory
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = collections.defaultdict(list) >>> for k,v in s: ... d[k].append(v) ... >>> d defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}) >>> d.items() dict_items([('yellow', [1, 3]), ('blue', [2, 4]), ('red', [1])]) >>> sorted(d.items()) [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
使用 dict 作为 default_factory
>>> nums = collections.defaultdict(dict) >>> nums[1] = {'one':1} >>> nums defaultdict(<class 'dict'>, {1: {'one': 1}}) >>> nums[2] {} >>> nums defaultdict(<class 'dict'>, {1: {'one': 1}, 2: {}})Python collections模块的使用方法
扫一扫手机访问
