简介
本文主要介绍python3下collections lib。主要lib如下:
– Counter
– defaultdict
– deque
– OrderedDict
– namedtuple
– ChainMap
Counter
计算出现次数
>>> import collections
>>> collections.Counter([1,1,2,3,4,4,4,5])
Counter({4: 3, 1: 2, 2: 1, 3: 1, 5: 1})
>>> collections.Counter("huuinn")
Counter({'n': 2, 'u': 2, 'h': 1, 'i': 1})
defaultdict
当对应的键值不存在时,返回默认值,而不是报错
>>> import collections
>>> d = collections.defaultdict(int)
>>> d[0]
0
>>> d[2]
0
>>> d = collections.defaultdict(lambda:100) # 想默认值非0时返回100时
>>> d[1]
100
>>> d[11]
100
>>> d = dict()
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
deque
可双向操作的队列
>>> import collections
>>> d = collections.deque([1,2,3,4])
>>> d.pop()
4
>>> d.popleft()
1
>>> d
deque([2, 3])
>>> d.appendleft(4)
>>> d.append(1)
>>> d
deque([4, 2, 3, 1])
OrderedDict
值按顺序添加到对象里
>>> import collections
>>> o = collections.OrderedDict()
>>> o['first']=1
>>> o['second']=2
>>> o
OrderedDict([('first', 1), ('second', 2)])
>>> o['second']=3
>>> o
OrderedDict([('first', 1), ('second', 3)])
namedtuple
让tuple类型的元素当作类成员属性来访问
>>> import collections
>>> N = collections.namedtuple('Fruit',['apple','grape'])
>>> N(*[1,2])
Fruit(apple=1, grape=2)
>>> n = N(*[1,2])
>>> n
Fruit(apple=1, grape=2)
>>> n.apple
1
>>> n.grape
2
ChainMap
多个字典合并
>>> import collections
>>> c = collections.ChainMap({1:2,3:4},{5:6,7:8})
>>> c = c.new_child({9:10,11:12})
>>> c
ChainMap({9: 10, 11: 12}, {1: 2, 3: 4}, {5: 6, 7: 8})
>>> c[9]
10
>>> c.maps
[{9: 10, 11: 12}, {1: 2, 3: 4}, {5: 6, 7: 8}]
>>> c.maps[0]
{9: 10, 11: 12}