溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python中實現(xiàn)計數(shù)的方法

發(fā)布時間:2020-07-06 16:07:18 來源:億速云 閱讀:443 作者:清晨 欄目:編程語言

這篇文章主要介紹python中實現(xiàn)計數(shù)的方法,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

python中實現(xiàn)計數(shù)的一般方法:

1、使用字典解決(dict)

字典計數(shù)是最常用的計數(shù)方法,逐個遍歷數(shù)據(jù)結(jié)構(gòu)中元素,將元素作為鍵,元素個數(shù)作為值進(jìn)行統(tǒng)計,依次加入字典中。

實例演示

test_lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'a', 'f', 's', 'b', 'h', 'k', 'i', 'j', 'c', 'd', 'f']
counter_dict = {}
for item in test_lst:if item in counter_dict: counter_dict[item] += 1 else: counter_dict[item] = 1print(counter_dict)

程序運行結(jié)果>>>{'i': 1, 'a': 2, 's': 1, 'g': 1, 'b': 2, 'k': 1, 'h': 1, 'j': 1, 'c': 2, 'e': 1, 'd': 2, 'f': 3}

2、使用dict.setdefault(key, dvalue)方法解決

可以使用dict.setdefault()方式進(jìn)行統(tǒng)計,比起直接使用dict,該方法不用使用if-else語句進(jìn)行判斷,且避免了KeyError異常。

實例演示

test_lst = ['a', 'b', 'c', 'd', 'eshi', 'f', 'g', 'a', 'f', 's', 'b', 'h', 'k', 'i', 'j', 'c', 'd', 'f']
counter_sdict = {}for item in test_lst:counter_sdict[item] = counter_sdict.setdefault(item, 0) + 1print(counter_sdict)

程序運行結(jié)果>>>{'k': 1, 'e': 1, 'c': 2, 'a': 2, 'b': 2, 'd': 2, 'f': 3, 'g': 1, 's': 1, 'j': 1, 'i': 1, 'h': 1}

同dict方法,但程序的容錯性比上面的方法要好,且數(shù)據(jù)量大時,該程序比使用dict的傳統(tǒng)方法要節(jié)省時間。

3、使用defaultdict類解決

defaultdict類的初始化函數(shù)接受一個類型作為參數(shù),當(dāng)所訪問的鍵不存在的時候,它自動實例化一個值作為默認(rèn)值。使用defaultdict與使用dict的區(qū)別在于,defaultdict能夠自動對獲取結(jié)果進(jìn)行排序,這就解決了我們后續(xù)排序的麻煩,并且defaushltdict是自帶“輪子”,就不用重新創(chuàng)造了,節(jié)省開發(fā)時間哦。

實例演示

from collections import defaultdict
test_lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'a', 'f', 's', 'b', 'h', 'k', 'i', 'j', 'c', 'd', 'f']
counter_ddict = defaultdict(int)for item in test_lst:counter_ddict[item] += 1print(counter_ddict)

程序運行結(jié)果>>>defaultdict(<class 'int'>, {'k': 1, 'e': 1, 'c': 2, 'a': 2, 'b': 2, 'd': 2, 'f': 3, 'g': 1, 's': 1, 'j': 1, 'i': 1, 'h': 1})

4、結(jié)合使用set和list兩種數(shù)據(jù)結(jié)構(gòu)來解決

思路如下:首先,初始化一個set和一個列表list,獲取序列中需要統(tǒng)計的元素;然后,依次遍歷set中的內(nèi)容,使用需要統(tǒng)計序列的cosut()方法,分別統(tǒng)計set中的內(nèi)容并計入新列表中。

實例演示

test_lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'a', 'f', 's', 'b', 'h', 'k', 'i', 'j', 'c', 'd', 'f']
r_lst = []temp = set(test_lst)for item in temp:r_lst.append((item, test_lst.count(item)))print(r_lst)

程序運行結(jié)果>>>[('j', 1), ('k', 1), ('a', 2), ('s', 1), ('d', 2), ('h', 1), ('f', 3), ('c', 2), ('e', 1), ('b', 2), ('i', 1), ('g', 1)]

以上是python中實現(xiàn)計數(shù)的方法的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI