[雪峰磁针石博客]python库介绍-collections:高性能容器数据类型
简介 2.4新增 源代码:Lib/collections.py and Lib/_abcoll.py 提供了替换dict, list, set和tuple的数据类型。 主要类型如下: namedtuple(): 命名元组,创建有名字域的元组子类的工厂函数。python 2.6新增。 deque:双端队列,类似于列表,两端进栈和出栈都比较快速。python 2.4新增。 Counter:字典的子类,用于统计哈希对象。python 2.7新增。 OrderedDict:有序字典,字典的子类,记录了添加顺序。python 2.7新增。 defaultdict:dict的子类,调用一个工厂函数支持不存在的值。python 2.5新增。 还提供了抽象基类,用来测试类是否提供了特殊接口,不管是哈希或者映射。 Counter 计数器(Counter)是一个容器,用来跟踪值出现了多少次。和其他语言中的bag或multiset类似。 计数器支持三种形式的初始化。构造函数可以调用序列,包含key和计数的字典,或使用关键字参数。 import collections print(collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])) print(collections.Counter({'a': 2, 'b': 3, 'c': 1})) print(collections.Counter(a=2, b=3, c=1)) 执行结果: $ python3 collections_counter_init.py Counter({'b': 3, 'a': 2, 'c': 1}) Counter({'b': 3, 'a': 2, 'c': 1}) Counter({'b': 3, 'a': 2, 'c': 1}) 注意key的出现顺序是根据计数的从大到小。 可以创建空的计数器,再update: import collections c = collections.Counter() print('Initial :{0}'.format(c)) c.update('abcdaab') print('Sequence:{0}'.format(c)) c.update({'a': 1, 'd': 5}) print('Dict :{0}'.format(c)) 执行结果: python3.5 collections_counter_update.py* Initial :Counter() Sequence:Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1}) Dict :Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1}) 访问计数 import collections c = collections.Counter('abcdaab') for letter in 'abcde': print('{0} : {1}'.format(letter, c[letter])) 执行结果: $ python3.5 collections_counter_get_values.py a : 3 b : 2 c : 1 d : 1 e : 0 注意这里不存在的元素也会统计为0。 elements方法可以列出所有元素: import collections c = collections.Counter('extremely') c['z'] = 0 print(c) print(list(c.elements())) 执行结果: $ python3.5 collections_counter_elements.py Counter({'e': 3, 'y': 1, 'r': 1, 'x': 1, 'm': 1, 'l': 1, 't': 1, 'z': 0}) ['y', 'r', 'x', 'm', 'l', 't', 'e', 'e', 'e'] 注意后面并没有输出计数为0的元素。 most_common()可以提取出最常用的元素。 import collections c = collections.Counter() with open('/etc/adduser.conf', 'rt') as f: for line in f: c.update(line.rstrip().lower()) print('Most common:') for letter, count in c.most_common(3): print('{0}: {1}'.format(letter, count)) 执行结果: $ python3.5 collections_counter_most_common.py Most common: : 401 e: 310 s: 221 Counter还支持算术和集合运算,它们都只会保留数值为正整数的key。 import collections import pprint c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']) c2 = collections.Counter('alphabet') print('C1:') pprint.pprint(c1) print('C2:') pprint.pprint(c2) print('\nCombined counts:') print(c1 + c2) print('\nSubtraction:') print(c1 - c2) print('\nIntersection (taking positive minimums):') print(c1 & c2) print('\nUnion (taking maximums):') print(c1 | c2) 执行结果: $ python3 collections_counter_arithmetic.py C1: Counter({'b': 3, 'a': 2, 'c': 1}) C2: Counter({'a': 2, 't': 1, 'l': 1, 'e': 1, 'b': 1, 'p': 1, 'h': 1}) Combined counts: Counter({'b': 4, 'a': 4, 'p': 1, 'e': 1, 'c': 1, 't': 1, 'l': 1, 'h': 1}) Subtraction: Counter({'b': 2, 'c': 1}) Intersection (taking positive minimums): Counter({'a': 2, 'b': 1}) Union (taking maximums): Counter({'b': 3, 'a': 2, 'p': 1, 'e': 1, 'c': 1, 't': 1, 'l': 1, 'h': 1}) 上面的例子让人觉得collections只能处理单个字符。其实不是这样的,请看标准库中的实例。 from collections import Counter import pprint import re cnt = Counter() for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: cnt[word] += 1 pprint.pprint(cnt) cnt = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue']) pprint.pprint(cnt) words = re.findall('\w+', open('/etc/adduser.conf').read().lower()) print(Counter(words).most_common(10)) 执行结果: $ python3 collections_counter_normal.py Counter({'blue': 3, 'red': 2, 'green': 1}) Counter({'blue': 3, 'red': 2, 'green': 1}) [('the', 27), ('is', 13), ('be', 12), ('if', 12), ('will', 12), ('user', 10), ('home', 9), ('default', 9), ('to', 9), ('users', 8)] 第1段代码和第2段的代码效果式样的,后面一段代码通过Counter实现了简单的单词的统计功能。比如面试题:使用python打印出/etc/ssh/sshd_config出现次数最高的10个单词及其出现次数。 下面看看Counter的相关定义: class collections.Counter([iterable-or-mapping]) 。注意Counter是无序的字典。在key不存在的时候返回0. c['sausage'] = 0。设置值为0不会删除元素,要使用del c['sausage']。 除了标准的字典方法,额外增加了: elements() :返回一个包含所有元素的迭代器,忽略小于1的计数。 most_common([n]):返回最常用的元素及其计数的列表。默认返回所有元素。 subtract([iterable-or-mapping]) :相减。 namedtuple 命名元组和普通元组的的内存效率差不多。它不会针对每个实例生成字典。 import collections Person = collections.namedtuple('Person', 'name age gender') print('Type of Person:{0}'.format(type(Person))) bob = Person(name='Bob', age=30, gender='male') print('\nRepresentation: {0}'.format(bob)) jane = Person(name='Jane', age=29, gender='female') print('\nField by name: {0}'.format(jane.name)) print('\nFields by index:') for p in [bob, jane]: print('{0} is a {1} year old {2}'.format(*p)) 执行结果: $ python3 collections_namedtuple_person.py Type of Person:<class 'type'> Representation: Person(name='Bob', age=30, gender='male') Field by name: Jane Fields by index: Bob is a 30 year old male Jane is a 29 year old female 从上例可以看出命名元组Person类和excel的表头类似,给下面的每个列取个名字,真正excel行数据则存储在Person类的实例中。好处在于可以jane.name这样的形式访问,比记元组的index要直观。 注意列名在实现内部其实是个标识符,所以不能和关键字冲突,只能用字母或者下划线开头。下例会报错: import collections try: collections.namedtuple('Person', 'name class age gender') except ValueError as err: print(err) try: collections.namedtuple('Person', 'name age gender age') except ValueError as err: print(err) 执行结果: $ python3 collections_namedtuple_bad_fields.py Type names and field names cannot be a keyword: 'class' Encountered duplicate field name: 'age' 设置rename=True,列名会在冲突时自动重命名,不过这种重命名并不美观。 import collections with_class = collections.namedtuple('Person', 'name class age gender', rename=True) print(with_class._fields) two_ages = collections.namedtuple('Person', 'name age gender age', rename=True) print(two_ages._fields) 执行结果: $ python collections_namedtuple_rename.py ('name', '_1', 'age', 'gender') ('name', 'age', 'gender', '_3') 定义 collections.namedtuple(typename, field_names, verbose=False) 返回一个命名元组类。如果verbose为True,会打印类定义信息 命名元组在处理数据库的时候比较有用: ChainMap 映射链 用于查找多个字典。 ChainMap管理一系列字典,按顺序根据key查找值。 访问值: API和字典类似。 collections_chainmap_read.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m = collections.ChainMap(a, b) print('Individual Values') print('a = {}'.format(m['a'])) print('b = {}'.format(m['b'])) print('c = {}'.format(m['c'])) print() print('m = {}'.format(m)) print('Keys = {}'.format(list(m.keys()))) print('Values = {}'.format(list(m.values()))) print() print('Items:') for k, v in m.items(): print('{} = {}'.format(k, v)) print() print('"d" in m: {}'.format(('d' in m))) 执行结果: $ python3 collections_chainmap_read.py Individual Values a = A b = B c = C m = ChainMap({'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'}) Keys = ['c', 'a', 'b'] Values = ['C', 'A', 'B'] Items: c = C a = A b = B "d" in m: False 调整顺序 collections_chainmap_reorder.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m = collections.ChainMap(a, b) print(m.maps) print('c = {}\n'.format(m['c'])) # reverse the list m.maps = list(reversed(m.maps)) print(m.maps) print('c = {}'.format(m['c'])) 执行结果: $ python3 collections_chainmap_reorder.py [{'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'}] c = C [{'c': 'D', 'b': 'B'}, {'c': 'C', 'a': 'A'}] c = D 更新值 更新原字典: collections_chainmap_update_behind.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m = collections.ChainMap(a, b) print('Before: {}'.format(m['c'])) a['c'] = 'E' print('After : {}'.format(m['c'])) 执行结果 $ python3 collections_chainmap_update_behind.py Before: C After : E 直接更新ChainMap: collections_chainmap_update_directly.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m = collections.ChainMap(a, b) print('Before:', m) m['c'] = 'E' print('After :', m) print('a:', a) 执行结果 $ python3 collections_chainmap_update_directly.py Before: ChainMap({'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'}) After : ChainMap({'c': 'E', 'a': 'A'}, {'c': 'D', 'b': 'B'}) a: {'c': 'E', 'a': 'A'} ChainMap可以方便地在前面插入字典,这样可以避免修改原来的字典。 collections_chainmap_new_child.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} m1 = collections.ChainMap(a, b) m2 = m1.new_child() print('m1 before:', m1) print('m2 before:', m2) m2['c'] = 'E' print('m1 after:', m1) print('m2 after:', m2) 执行结果 $ python3 collections_chainmap_new_child.py m1 before: ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}) m2 before: ChainMap({}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}) m1 after: ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}) m2 after: ChainMap({'c': 'E'}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'}) 还可以通过传入字典的方式 collections_chainmap_new_child_explicit.py import collections a = {'a': 'A', 'c': 'C'} b = {'b': 'B', 'c': 'D'} c = {'c': 'E'} m1 = collections.ChainMap(a, b) m2 = m1.new_child(c) print('m1["c"] = {}'.format(m1['c'])) print('m2["c"] = {}'.format(m2['c'])) 执行结果 $ python3 collections_chainmap_new_child_explicit.py m1["c"] = C m2["c"] = E 另外一种等价的方式: m2 = collections.ChainMap(c, *m1.maps) 参考资料 本文最新版本地址 讨论 钉钉免费群21745728 qq群144081101 567351477 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 python官方文档:https://docs.python.org/3/library/collections.html https://pymotw.com/3/collections/chainmap.html http://collections-extended.lenzm.net/ https://pypi.python.org/pypi/collections-extended/ 本文代码地址