python出现的次数最多的元素_Python cookbook(数据结构与算法)找出序列中出现次数最多的元素算...
本文實例講述了Python找出序列中出現次數最多的元素。分享給大家供大家參考,具體如下:
問題:找出一個元素序列中出現次數最多的元素是什么
解決方案:collections模塊中的Counter類正是為此類問題所設計的。它的一個非常方便的most_common()方法直接告訴你答案。
# Determine the most common words in a list
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]from collections import Counter
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
# outputs [('eyes', 8), ('the', 5), ('look', 4)]# Example of merging in more words
morewords = ['why','are','you','not','looking','in','my','eyes']word_counts.update(morewords) #使用update()增加計數
print(word_counts.most_common(3))
>>> ================================ RESTART ================================
>>>
[('eyes', 8), ('the', 5), ('look', 4)][('eyes', 9), ('the', 5), ('my', 4)]>>>
在底層實現中,Counter是一個字典,在元素和它們出現的次數間做了映射。
>>> word_counts
Counter({'eyes': 9, 'the': 5, 'my': 4, 'look': 4, 'into': 3, 'around': 2, 'not': 2, "don't": 1, 'under': 1, 'are': 1, 'looking': 1, "you're": 1, 'you': 1, 'why': 1, 'in': 1})
>>> word_counts.most_common(3) #top_three
[('eyes', 9), ('the', 5), ('my', 4)]>>> word_counts['not']2
>>> word_counts['eyes']9
>>> word_counts['eyes']+1
10
>>> word_counts
Counter({'eyes': 9, 'the': 5, 'my': 4, 'look': 4, 'into': 3, 'around': 2, 'not': 2, "don't": 1, 'under': 1, 'are': 1, 'looking': 1, "you're": 1, 'you': 1, 'why': 1, 'in': 1})
>>> word_counts['eyes']=word_counts['eyes']+1 #手動增加元素計數
>>> word_counts
Counter({'eyes': 10, 'the': 5, 'my': 4, 'look': 4, 'into': 3, 'around': 2, 'not': 2, "don't": 1, 'under': 1, 'are': 1, 'looking': 1, "you're": 1, 'you': 1, 'why': 1, 'in': 1})
>>>
增加元素出現次數可以通過手動進行增加,也可以借助update()方法;
另外,Counter對象另一個特性是它們可以同各種數學運算操作結合起來使用:
>>> a=Counter(words)
>>> a
Counter({'eyes': 8, 'the': 5, 'look': 4, 'my': 3, 'into': 3, 'around': 2, 'under': 1, "you're": 1, 'not': 1, "don't": 1})
>>> b=Counter(morewords)
總結
以上是生活随笔為你收集整理的python出现的次数最多的元素_Python cookbook(数据结构与算法)找出序列中出现次数最多的元素算...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 40个创意简约型单页网站
- 下一篇: python编程神器下载_Python编