人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動態(tài)

5種Python統(tǒng)計次數(shù)方法技巧

發(fā)布日期:2021-12-14 01:55 | 文章來源:站長之家

一、使用字典 dict 統(tǒng)計

循環(huán)遍歷出一個可迭代對象的元素,如果字典中沒有該元素,那么就讓該元素作為字典的鍵,并將該鍵賦值為1,如果存在則將該元素對應(yīng)的值加1。

lists = ['a','a','b',1,2,3,1]
count_dist = dict()
for i in lists:
 if i in count_dist:
  count_dist[i] += 1
 else:
  count_dist[i] = 1
print(count_dist)
# {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1}

二、使用 collections.defaultdict 統(tǒng)計

defaultdict(parameter) 接受一個類型參數(shù),例如:int、float、str 等。

傳遞進來的類型參數(shù),不是用來約束值的類型,更不是約束鍵的類型,而是當鍵不存在時,實現(xiàn)一種值的初始化。

defaultdict(int) -- 初始化為0
defaultdict(float) -- 初始化為0.0
defaultdict(str) -- 初始化為''
from collections import defaultdict
lists = ['a','a','b',1,2,3,1]
count_dict = defaultdict(int)
for i in lists:
 count_dict[i] += 1
print(count_dict)
# defaultdict(<class 'int'>, {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1})

三、List count方法

count() 方法用于統(tǒng)計某個元素在列表中出現(xiàn)的次數(shù)。

使用語法:

# 使用語法
list.count(obj) # 返回次數(shù)

統(tǒng)計單個對象次數(shù):

# 統(tǒng)計單個對象次數(shù)
aList = [123, 'abc', 'good', 'abc', 123]
print("Count for 123 :", aList.count(123))
print("Count for abc :", aList.count('abc'))
# Count for 123 : 2
# Count for abc : 2

統(tǒng)計List中每一個對象次數(shù):

test = ["aaa","bbb","aaa","aaa","ccc","ccc","ddd","aaa","ddd","eee","ddd"]
print(test.count("aaa"))
# 4
print(test.count("bbb"))
# 1
test_result = []
for i in test:
 if i not in test_result:
  test_result.append(i)
print(test_result)
for i in test_result:
 print(f"{i}:{test.count(i)}")
'''
4
1
['aaa', 'bbb', 'ccc', 'ddd', 'eee']
aaa:4
bbb:1
ccc:2
ddd:3
eee:1
'''

四、使用集合(set)和列表(list)統(tǒng)計

先用 set 去重,然后循環(huán)把每一個元素和對應(yīng)的次數(shù) list.count(item) 組成元組。

'''
學(xué)習(xí)中遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流群:531509025
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書!
'''
lists = ['a','a','b',1,2,3,1]
count_set = set(lists)
print(count_set) # 集合去重
# {1, 2, 3, 'b', 'a'}
count_list = list()
for i in count_set:
 count_list.append((i, lists.count(i)))
print(count_list) 
# [(1, 2), (2, 1), (3, 1), ('b', 1), ('a', 2)]

五、collections.Counter方法

Counter 是一個容器對象,使用 collections 模塊中的 Counter 類可以實現(xiàn) hash 對象的統(tǒng)計。

Counter 是一個無序的容器類型,以字典的鍵值對形式存儲,其中元素作為 key,其計數(shù)作為 value。

計數(shù)值可以是任意的 Interger(包括0和負數(shù))。

Counter() 對象還有幾個可調(diào)用的方法:

  • most_common(n) -- TOP n 個出現(xiàn)頻率最高的元素
  • elements -- 獲取所有的鍵 通過list轉(zhuǎn)化
  • update -- 增加對象
  • subtrct -- 刪除對象
  • 下標訪問 a['xx'] --不存在時返回0
import collections
c = collections.Counter('helloworld')

直接顯示各個元素頻次

print(c)
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})

使用 most_common顯示最多的n個元素

當多個元素計數(shù)值相同時,排列是無確定順序的。

print(c.most_common(3))
# [('l', 3), ('o', 2), ('h', 1)]

使用數(shù)組下標獲取,類似字典方式:

print("The number of 'o':", c['o'])
# The number of 'o': 2

統(tǒng)計列表: (只要列表中對象都是可以哈希的)

import collections
x = [1,2,3,4,5,6,7,8,1,8,8,8,4,3,5]
c = collections.Counter(x)
print(c)
# Counter({1: 2, 2: 1, 3: 2, 4: 2, 5: 2, 6: 1, 7: 1, 8: 4})
print(c.most_common(3))
# [(8, 4), (1, 2), (3, 2)]
dictc = dict(c) # 轉(zhuǎn)換為字典
print(dictc)
# {1: 2, 2: 1, 3: 2, 4: 2, 5: 2, 6: 1, 7: 1, 8: 4}

如果列表中有 unhashalbe 對象,例如:可變的列表,是無法統(tǒng)計的。

元組也可以統(tǒng)計。

c = collections.Counter([[1,2], "hello", 123, 0.52])
# TypeError: unhashable type: 'list'

得到 Counter 計數(shù)器對象之后,還可以在此基礎(chǔ)上進行增量更新。

elements() -- 返回迭代器

元素排列無確定順序,個數(shù)小于1的元素不被包含。

'''
學(xué)習(xí)中遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流群:531509025
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書!
'''
import collections
c = collections.Counter(a=4,b=2,c=1)
print(c)
# Counter({'a': 4, 'b': 2, 'c': 1})
list(c.elements())
# ['a', 'a', 'a', 'a', 'b', 'b', 'c']

subtract函數(shù) -- 減去元素

import collections
c = collections.Counter(["a","b","c","a"])
print(c)
# Counter({'a': 2, 'b': 1, 'c': 1})
print(list(c.elements())) # 展開
# ['a', 'a', 'b', 'c']
# 減少元素
c.subtract(["a","b"])
print(c)
# Counter({'a': 1, 'c': 1, 'b': 0})
print(list(c.elements()))
# ['a', 'c']

update函數(shù) -- 增加元素

在進行增量計數(shù)時候,update函數(shù)非常有用。

'''
學(xué)習(xí)中遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流群:531509025
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學(xué)習(xí)教程和PDF電子書!
'''
import collections
c = collections.Counter(["a","b","c","a"])
print(c)
# Counter({'a': 2, 'b': 1, 'c': 1})
print(list(c.elements())) # 展開
# ['a', 'a', 'b', 'c']
c.update(["a","d"])
print(c)
# Counter({'a': 3, 'b': 1, 'c': 1, 'd': 1})
print(list(c.elements()))
# ['a', 'a', 'a', 'b', 'c', 'd']

del函數(shù) -- 刪除鍵

當計數(shù)值為0時,并不意味著元素被刪除,刪除元素應(yīng)當使用del。

import collections
c = collections.Counter('helloworld')
print(c)
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})
c["d"] = 0
print(c)
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 0})
del c["l"]
print(c)
# Counter({'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 0})

到此這篇關(guān)于5種Python統(tǒng)計次數(shù)方法技巧的文章就介紹到這了,更多相關(guān)Python內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!

版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實時開通

自選配置、實時開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對1客戶咨詢顧問

在線
客服

在線客服:7*24小時在線

客服
熱線

400-630-3752
7*24小時客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部