最近在刷leetcode,发现很多题目的思路都很相似。其中,collections模块中的Counter()多次在习题中碰到,很有必要对该知识点总结一下,加深理解。
1.collections模块
collections模块自Python 2.4 版本之后,引入除了dict、list、set、tuple以外的一些特俗容器,分别是:
- namedtuple():factory function for creating tuple subclasses with named fields(version 2.6)
- deque:list-like container with fast appends and pops on either end(version 2.4)
- Counter:dict subclass for counting hashable objects(version 2.7)
- OrderdDict:dict subclass that remembers the order entries were added(version 2.7)
- defaultdict:dict subclass that calls a factory function to supply missing values(version 2.5)
具体文档参考:https://docs.python.org/2/library/collections.html
2.Counter()
计数器(counter)是一个无序容器,用来跟踪值出现的次数。
2.1 创建