python中統計計數的幾種方法和Counter的介紹


1) 使用字典dict()

1) 使用字典dict()

循環遍歷出一個可迭代對象中的元素,如果字典沒有該元素,那么就讓該元素作為字典的鍵,並將該鍵賦值為1,如果存在就將該元素對應的值加1.

lists = ['a','a','b',5,6,7,5]
		count_dict = dict()
		for item in lists:
			if item in count_dict:
				count_dict[item] += 1
			else:
				count_dict[item] = 1

2) 使用defaultdict()

defaultdict(parameter) 可以接受一個類型參數,如str,int等,但傳遞進來的類型參數,不是用來約束值的類型,更不是約束鍵的類型,而是當鍵不存在的話,實現一種值的初始化

  1. defaultdict(int):初始化為 0
  2. defaultdict(float):初始化為 0.0
  3. defaultdict(str):初始化為 ''
from collections import defaultdict
		lists = ['a', 'a', 'b', 5, 6, 7, 5]
		count_dict = defaultdict(int)
		for item in lists:
			count_dict[item] += 1

3)使用集合(set)和列表(list)

先使用set去重,然后循環的把每一個元素和每一個元素對應的次數lists.count(item)組成一個元組放在列表里面

lists = ['a', 'a', 'b', 5, 6, 7, 5]
count_set = set(lists)
count_list = list()
for item in count_set:
	count_list.append((item,lists.count(item))

4)使用Counter

Counter是一個容器對象,主要的作用是用來統計散列對象,可以使用三種方式來初始化

  1. 參數里面參數可迭代對象 Counter("success")
  2. 傳入關鍵字參數Counter((s=3,c=2,e=1,u=1))
  3. 傳入字典 Counter({"s":3,"c"=2,"e"=1,"u"=1})

Counter()對象還有幾個可以調用的方法,代碼里面分別進行了說明

from collections import Counter
lists = ['a', 'a', 'b', 5, 6, 7, 5]
a = Counter(lists)
print(a)  # Counter({'a': 2, 5: 2, 'b': 1, 6: 1, 7: 1})
a.elements() # 獲取a中所有的鍵,返回的是一個對象,我們可以通過list來轉化它
a.most_common(2) # 前兩個出現頻率最高的元素已經他們的次數,返回的是列表里面嵌套元組
a['zz']  # 訪問不存在的時候,默認返回0
a.update("aa5bzz") # 更新被統計的對象,即原有的計數值與新增的相加,而不是替換
a.subtrct("aaa5z") # 實現與原有的計數值相減,結果運行為0和負值


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM