国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python cookbook(數據結構與算法)找出序列中出現次數最多的元素算法示例

2020-01-04 15:38:03
字體:
來源:轉載
供稿:網友

本文實例講述了Python找出序列中出現次數最多的元素。分享給大家供大家參考,具體如下:

問題:找出一個元素序列中出現次數最多的元素是什么

解決方案:collections模塊中的Counter類正是為此類問題所設計的。它的一個非常方便的most_common()方法直接告訴你答案。

# Determine the most common words in a listwords = [  '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 Counterword_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 wordsmorewords = ['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_countsCounter({'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']+110>>> word_countsCounter({'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_countsCounter({'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)>>> aCounter({'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)>>> bCounter({'not': 1, 'my': 1, 'in': 1, 'you': 1, 'looking': 1, 'are': 1, 'eyes': 1, 'why': 1})>>> c=a+b>>> cCounter({'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, 'in': 1, 'why': 1})>>> # substract counts>>> d=a-b>>> dCounter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2, 'under': 1, "you're": 1, "don't": 1})>>>

當面對任何需要對數據制表或計數的問題時,Counter對象都是你手邊的得力工具。比起利用字典自己手寫算法,更應采用該方式完成任務。

 

希望本文所述對大家Python程序設計有所幫助。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 淮北市| 大连市| 安顺市| 平昌县| 兴安县| 阿拉尔市| 罗江县| 晴隆县| 太谷县| 旌德县| 廊坊市| 芦山县| 凤翔县| 舞钢市| 象山县| 内黄县| 友谊县| 麦盖提县| 兴安盟| 金昌市| 邓州市| 玛沁县| 京山县| 尚义县| 红安县| 吴川市| 唐山市| 建湖县| 南雄市| 民县| 通城县| 云龙县| 浦北县| 四川省| 贞丰县| 温泉县| 姜堰市| 滕州市| 甘泉县| 民丰县| 阳原县|