有时,我们会在一个包含多个重复元素的序列中,查找出现次数最多的元素。
data = ['a', 'b', 'c', 'a', 't', 'p', 't', 'a', 'b', 'c', 'c', 'a', 't', 'p',
'l', 'm', 'n', 'b', 'd', 'l', 'l', 'm', 'n', 'b', 'd', 'l', 'd', 'l',
'l', 'c', 'a', 't', 'p', 'eyes', 'kind', 'option', 'w', 'q', 'w', 'e',
'o', 'p', 'q', 'r', 's', 't', 'c', 'a', 't', 'p', 'eyes', 'q', 'w', 'e']
from collections import Counter
counters = Counter(data)
at_most = counters.most_common(3)
print(at_most)
输出结果
[('a', 6), ('t', 6), ('l', 6)]
Counter对象接受任何可哈希的序列对象,在底层中,Counter是一个字典,在元素和他们出现的次数做了一个映射。
Counter对象也可以应用各种数学运算。
a = Counter(('a', 'b', 'c', 'd', 'a'))
b = Counter(('b', 'c', 'c', 'e', 'f', 'h'))
print(a+b)
print(a-b)
Counter({'c': 3, 'a': 2, 'b': 2, 'd': 1, 'e': 1, 'f': 1, 'h': 1})
Counter({'a': 2, 'd': 1})
其他用法
a = Counter(('a', 'b', 'c', 'd', 'a'))
b = Counter(('b', 'c', 'c', 'e', 'f', 'h'))
a.update(b)
print(a)
for i in a.elements():
print(i)
Counter({'c': 3, 'a': 2, 'b': 2, 'd': 1, 'e': 1, 'f': 1, 'h': 1})
a
a
b
b
c
c
c
d
e
f
h