统计序列每个元素出现的次数。
>>> from collections import Counter
>>> s = 'python+py'
>>> counter = Counter(s)
>>> counter
Counter({'p': 2, 'y': 2, 't': 1, 'h': 1, 'o': 1, 'n': 1, '+': 1})
返回的结果类似字典,可以使用字典的相关方法。
>>> counter.keys()
dict_keys(['p', 'y', 't', 'h', 'o', 'n', '+'])
>>> counter.values()
dict_values([2, 2, 1, 1, 1, 1, 1])
>>> counter.items()
dict_items([('p', 2), ('y', 2), ('t', 1), ('h', 1), ('o', 1), ('n', 1), ('+', 1)])
统计出现次数最多的两个元素。
>>> counter.most_common(2)
[('p', 2), ('y', 2)]