在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。
1.namedtuple: 生成可以使用名字来访问元素内容的tuple
1 import collections 2 name_tuple = collections.namedtuple("birthday", ["Year", "Month", "Day", "Hour", "Minute"]) 3 new_tuple = name_tuple("1990","12","22","4","35") 4 print(new_tuple) 5 print(new_tuple.Day)
结果对照:
1 birthday(Year='1990', Month='12', Day='22', Hour='4', Minute='35') 2 22
2.deque: 双向队列,可以快速的从另外一侧追加和推出对象
1 from collections import deque 2 q = deque(['a', 'b', 'c']) 3 q.append('x') 4 q.appendleft('y') 5 print(q) 6 7 q.pop() 8 q.popleft() 9 print(q)
结果对照:
1 deque(['y', 'a', 'b', 'c', 'x']) 2 deque(['a', 'b', 'c'])
3.defaultdict: 带有默认值的字典
1 from collections import defaultdict 2 dd = defaultdict(lambda: 'N/A') # 使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值 3 dd['key1'] = 'abc' 4 print(dd['key1']) # key1存在 5 6 print(dd['key2']) # key2不存在,返回默认值
结果对照:
1 abc 2 N/A
1 from collections import defaultdict 2 values = [11, 22, 33,44,55,66,77,88,99,90] 3 my_dict = defaultdict(list) 4 5 for value in values: 6 if value>66: 7 my_dict['k1'].append(value) 8 else: 9 my_dict['k2'].append(value) 10 11 print(my_dict)
结果对照:
1 defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})
3.Counter: 计数器,主要用来计数,返回字典形式
1 from collections import Counter 2 c = Counter('abcdeabcdabcaba') 3 print(c)
结果对照:
1 Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})