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

首頁 > 編程 > Python > 正文

利用Python找出序列中出現(xiàn)最多的元素示例代碼

2020-02-16 10:59:55
字體:
供稿:網(wǎng)友

前言

Python包含6種內(nèi)置的序列:列表、元組、字符串 、Unicode字符串、buffer對象、xrange對象。在序列中的每個元素都有自己的編號。列表與元組的區(qū)別在于,列表是可以修改,而組元不可修改。理論上幾乎所有情況下元組都可以用列表來代替。有個例外是但元組作為字典的鍵時,在這種情況下,因?yàn)殒I不可修改,所以就不能使用列表。

我們在一些統(tǒng)計工作或者分析過程中,有事會遇到要統(tǒng)計一個序列中出現(xiàn)最多次的元素,比如一段英文中,查詢出現(xiàn)最多的詞是什么,及每個詞出現(xiàn)的次數(shù)。一遍的做法為,將每個此作為key,出現(xiàn)一次,value增加1。

例如:

morewords = ['why','are','you','not','looking','in','my','eyes']for word in morewords: word_counts[word] += 1

collections.Counter 類就是專門為這類問題而設(shè)計的, 它甚至有一個有用的 most_common() 方法直接給了你答案。

collections模塊

collections模塊自Python 2.4版本開始被引入,包含了dict、set、list、tuple以外的一些特殊的容器類型,分別是:

OrderedDict類:排序字典,是字典的子類。引入自2.7。 namedtuple()函數(shù):命名元組,是一個工廠函數(shù)。引入自2.6。 Counter類:為hashable對象計數(shù),是字典的子類。引入自2.7。 deque:雙向隊(duì)列。引入自2.4。 defaultdict:使用工廠函數(shù)創(chuàng)建字典,使不用考慮缺失的字典鍵。引入自2.5。

文檔參見:http://docs.python.org/2/library/collections.html。

Counter類

Counter類的目的是用來跟蹤值出現(xiàn)的次數(shù)。它是一個無序的容器類型,以字典的鍵值對形式存儲,其中元素作為key,其計數(shù)作為value。計數(shù)值可以是任意的Interger(包括0和負(fù)數(shù))。Counter類和其他語言的bags或multisets很相似。

為了演示,先假設(shè)你有一個單詞列表并且想找出哪個單詞出現(xiàn)頻率最高。你可以這樣做:

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 Counterword_counts = Counter(words)# 出現(xiàn)頻率最高的3個單詞top_three = word_counts.most_common(3)print(top_three)# Outputs [('eyes', 8), ('the', 5), ('look', 4)]

另外collections.Counter還有一個比較高級的功能,支持?jǐn)?shù)學(xué)算術(shù)符的相加相減。

>>> a = Counter(words)>>> b = Counter(morewords)>>> aCounter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2,"you're": 1, "don't": 1, 'under': 1, 'not': 1})>>> bCounter({'eyes': 1, 'looking': 1, 'are': 1, 'in': 1, 'not': 1, 'you': 1,'my': 1, 'why': 1})>>> # Combine counts>>> c = a + b>>> cCounter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2,'around': 2, "you're": 1, "don't": 1, 'in': 1, 'why': 1,'looking': 1, 'are': 1, 'under': 1, 'you': 1})>>> # Subtract counts>>> d = a - b>>> dCounter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2,"you're": 1, "don't": 1, 'under': 1})>>>            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 新巴尔虎左旗| 舟曲县| 鹿泉市| 正宁县| 云林县| 富顺县| 盘山县| 社旗县| 万宁市| 阿荣旗| 灵璧县| 城口县| 漳平市| 永丰县| 文昌市| 吉木乃县| 若羌县| 洛南县| 威远县| 慈溪市| 沙湾县| 法库县| 玉林市| 无为县| 尉氏县| 榆林市| 蒙自县| 南丰县| 资中县| 洛宁县| 扬中市| 舒兰市| 阿拉善盟| 柘荣县| 绍兴市| 桂平市| 玛沁县| 锡林郭勒盟| 五指山市| 广汉市| 邓州市|