Python内建模块 collections
官方文档:https://docs.python.org/3.6/library/collections.html#module-collections
当遇到了新的类型再更新。
仅记录LeetCode比较常用的语法,别的请参考官方文档。
Counter
: dict subclass for counting hashable objects
可以通过一个迭代器来创建Counter,其他的方法类似字典。此外,比起字典,定义了该类型的+-&|
。
>>> from collections import Counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c
Counter({'g': 1, 'a': 3, 'l': 2, 'h': 1, 'd': 1})
>>> c['c'] # count of a missing element is zero
0
>>> c['s'] = 0 # counter entry with a zero count
>>> del c['s'] # del actually removes the entry
>>> c.most_common(3)
[('a', 3), ('l', 2), ('g', 1)]
deque
: list-like container with fast appends and pops on either end
Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). deque适合用于队列和栈:deque除了实现list的append()
和pop()
外,还支持appendleft()
和popleft()
,这样就可以非常高效地往头部添加或删除元素。
>>> from collections import deque
>>> q = deque(['a', 'b', 'c']) # 创建deque
>>> q.append('x') # 右边添加
>>> q.appendleft('y') # 左边添加
>>> q
deque(['y', 'a', 'b', 'c', 'x'])
>>>
>>> q[0] # 也可以进行索引
y
>>>
>>> q.pop() # 右边弹出
'x'
>>> q
deque(['y', 'a', 'b', 'c'])
>>> q.popleft() # 左边弹出
'y'
>>> q
deque(['a', 'b', 'c'])