Python實用技法第11篇:找出序列中出現次數最多的元素

Mark發表於2019-02-16

上一篇文章:Python實用技法第10篇:對切片命名
下一篇文章:Python實用技法第12篇:通過公共鍵對字典列表排序:itemgetter

1、需求?

我們有一個元素序列,想知道在序列中出現次數最多的元素是什麼?

2、解決方案?

collections模組中國的Counter類正是為此類問題而設計的。它甚至有一個非常方便的most_common()方法可以告訴我們答案。可以給Counter物件提供任何可雜湊的物件序列作為輸入。

  • 例項:假設一個列表,其中有一些列的單詞,我們想找出哪些單詞出現的最為頻繁:
from collections import Counter
words=[
`a`,`b`,`c`,`d`,`e`,`f`,
`a`,`b`,`c`,`d`,`e`,`f`,
`a`,`b`,`c`,
`a`,`b`,
`a`
]
#利用Counter統計每個元素出現的個數
words_counts=Counter(words)
#出現次數最多的3個元素
top_three=words_counts.most_common(3)
#返回元素和出現次數
print(top_three)

#Counter底層是一個字典,可以在元素和他們出現的次數之間做對映,例如:
#輸出元素【f】出現的次數
print(words_counts[`f`])

#如果想手動增加計數個數,只需要簡單的自增
words_counts[`f`]+=1
print(words_counts[`f`])

#如果想手動增加計數個數,還可以使用update()方法:
#只針對元素【f】增加一次計數
words_counts.update(`f`)
print(words_counts[`f`])

#為所有計數增加一次
morewords=[
`a`,`b`,`c`,`d`,`e`,`f`
]
words_counts.update(morewords)
print(words_counts[`f`])

執行結果:

[(`a`, 5), (`b`, 4), (`c`, 3)]
2
3
4
5
  • Counter物件另一個不為人知的特性,那就是他們可以輕鬆地同各種數學運算操作結合起來使用。
from collections import Counter
words1=[
`a`,`b`,`c`,`d`,`e`,`f`,
`a`,`b`,`c`,`d`,`e`,`f`,
`a`,`b`,`c`,
`a`,`b`,
`a`
]

words2=[
`a`,`b`,`c`,`d`,`e`,`f`,
`a`,`b`,`c`,
`a`,`b`,
`a`
]
one=Counter(words1)
two=Counter(words2)
print(one)
print(two)

three=one+two
print(three)

four=one-two
print(four)

執行結果:

Counter({`a`: 5, `b`: 4, `c`: 3, `d`: 2, `e`: 2, `f`: 2})
Counter({`a`: 4, `b`: 3, `c`: 2, `d`: 1, `e`: 1, `f`: 1})
Counter({`a`: 9, `b`: 7, `c`: 5, `d`: 3, `e`: 3, `f`: 3})
Counter({`a`: 1, `b`: 1, `c`: 1, `d`: 1, `e`: 1, `f`: 1})

上一篇文章:Python實用技法第10篇:對切片命名
下一篇文章:Python實用技法第12篇:通過公共鍵對字典列表排序:itemgetter

相關文章