新聞中心
在企業(yè)管理中,掌握豐富的統(tǒng)計(jì)信息資源,在通過科學(xué)的分析方法和先進(jìn)的技術(shù)手段,深入開展綜合分析和專題研究,可以為科學(xué)決策和管理提供各種可供選擇的咨詢建議與對策方案。可以看出,作為第一關(guān)的統(tǒng)計(jì)至關(guān)重要。小編之前向大家介紹了統(tǒng)計(jì)函數(shù)count的使用方法(https://www.py.cn/jishu/jichu/21678.html),其實(shí)python中發(fā)揮統(tǒng)計(jì)作用的不止count函數(shù),還有計(jì)數(shù)模塊counter,下面我們來看看吧。

1、counter
在python中是一個(gè)計(jì)數(shù)器。是dict的子類,計(jì)算可hash的對象。
主要功能:可以支持方便、快速的計(jì)數(shù),將元素?cái)?shù)量統(tǒng)計(jì),然后計(jì)數(shù)并返回一個(gè)字典,鍵為元素,值為元素個(gè)數(shù)。
2、counter創(chuàng)建的四種方法:
>>> c = Counter() # 創(chuàng)建一個(gè)空的Counter類
>>> c = Counter('gallahad') # 從一個(gè)可iterable對象(list、tuple、dict、字符串等)創(chuàng)建
>>> c = Counter({'a': 4, 'b': 2}) # 從一個(gè)字典對象創(chuàng)建
>>> c = Counter(a=4, b=2) # 從一組鍵值對創(chuàng)建3、使用示例
計(jì)數(shù)的例子:統(tǒng)計(jì)一個(gè)文件中每個(gè)單詞出現(xiàn)的次數(shù)
# 普通青年
d = {}
with open('/etc/passwd') as f:
for line in f:
for word in line.strip().split(':'):
if word not in d:
d[word] = 1
else:
d[word] += 1
# 文藝青年
d = defaultdict(int)
with open('/etc/passwd') as f:
for line in f:
for word in line.strip().split(':'):
d[word] += 1
# 棒棒的青年
word_counts = Counter()
with open('/etc/passwd') as f:
for line in f:
word_counts.update(line.strip().split(':'))以上就是對計(jì)數(shù)模塊counter的介紹,counter方便、快速的幫助我們計(jì)算,上面的使用方法要掌握哦~
本文題目:創(chuàng)新互聯(lián)Python教程:如何使用python計(jì)數(shù)模塊counter?
文章網(wǎng)址:http://www.5511xx.com/article/dhojdod.html


咨詢
建站咨詢
