counter()函数和most_common()函数
most_common()函數(shù)是collections模塊中counter類的函數(shù),當(dāng)我們使用它時(shí),首先要導(dǎo)入collections模塊
counter()函數(shù)返回的是一個(gè)類似于字典的counter計(jì)數(shù)器,如下:
?
Counter類中的most_common(n)函數(shù):
傳進(jìn)去一個(gè)可選參數(shù)n(代表獲取數(shù)量最多的前n個(gè)元素,如果不傳參數(shù),代表返回所有結(jié)果)
return返回一個(gè)列表(里面的元素是一個(gè)元組,元組第0位是被計(jì)數(shù)的具體元素,元組的第1位是出現(xiàn)的次數(shù),如:[('a',1),[('b'),2],[('c',3)]])當(dāng)多個(gè)元素計(jì)數(shù)值相同時(shí),按照字母序排列。
most_common()函數(shù)的源碼:
import heapq as _heapq def most_common(self, n=None):if n is None:return sorted(self.iteritems(), key=_itemgetter(1), reverse=True)return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))由源碼可知,most_commom()函數(shù)不傳參數(shù)值時(shí),用sort()函數(shù)排序,排序的根據(jù)是以第2個(gè)元素?cái)?shù)值進(jìn)行排序的,返回的是從大到小的順序的所有結(jié)果,如果有參數(shù)n,調(diào)用了?heapq模塊中的?nlargest?函數(shù)返回的前n個(gè)的元素結(jié)果。(其中?_heapq是上邊導(dǎo)入時(shí)將heapq?重命名成了?_heapq)
其中heapq.nlargest()函數(shù)功能類似于如下的函數(shù):
sorted(iterable, key=key, reverse=True)[:n]most_commom()函數(shù)用法示例如下
>>> from collections import Counter >>> a=[1,2,4,5,6,4,6,8,9,1,1,2,5,9] >>> b=Counter(a) >>> print(b) Counter({1: 3, 2: 2, 4: 2, 5: 2, 6: 2, 9: 2, 8: 1}) >>> type(b) <class 'collections.Counter'> >>> list=b.most_common(5) #取前5的結(jié)果,它不管第6個(gè)或后面的值是否與第5個(gè)值相等,只返回前5 >>> list [(1, 3), (2, 2), (4, 2), (5, 2), (6, 2)]most_common()函數(shù)返回的結(jié)果是元組列表,不是字典
most_common()函數(shù)的缺點(diǎn):在于它只返回前n個(gè)結(jié)果,他不管第n+1個(gè)或后面的值是否與第n個(gè)值相等,只單純的返回前n個(gè)值。
解決方法:
#返回統(tǒng)計(jì)單詞數(shù)出現(xiàn)最多的前n個(gè)單詞列表,如果第n+1與第n個(gè)相等可以一起并列的返回 def get_count(dct, n):data = dct.most_common()if(len(data)<=n):return list(data)else:val = data[n-1][1] return list(takewhile(lambda x: x[1] >= val, data)) #返回序列,當(dāng)predicat?
總結(jié)
以上是生活随笔為你收集整理的counter()函数和most_common()函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 进程的组织
- 下一篇: totorisgit与git两种方式pu