1. 程式人生 > >python獲取序列中元素及其出現的次數

python獲取序列中元素及其出現的次數

有時,我們會在一個包含多個重複元素的序列中,查找出現次數最多的元素。

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