参考:https://docs.python.org/2/library/collections.html#collections.Counter
1、Counter类创建的四种方法:
import collections
c = collections.Counter() # 创建一个空的Counter类
print(c)
c = collections.Counter('gallahad') # 从一个可iterable对象(list、tuple、dict、字符串等)创建
print(c)
c = collections.Counter({'a': 4, 'b': 2}) # 从一个字典对象创建
print(c)
c = collections.Counter(a=4, b=2) # 从一组键值对创建
print(c)
输出:
Counter()
Counter({'a': 3, 'l': 2, 'h': 1, 'g': 1, 'd': 1})
Counter({'a': 4, 'b': 2})
Counter({'a': 4, 'b': 2})
2、计数值的访问与缺失的键:
c = collections.Counter("abcdefgab")
print(c["a"])
print(c["b"])
print(c["c"])
print(c["h"])
输出:
2
2
1
0