新聞中心
此映射類型為鍵準(zhǔn)備了一個(gè)整數(shù)計(jì)數(shù)器。每更新一次鍵,該計(jì)數(shù)器就增加一次。因此,此類型可用于為可散列表對(duì)象計(jì)數(shù),或?qū)⑵渥鳛槎嘀丶鲜褂谩嘀丶暇褪羌现械脑乜梢远啻纬霈F(xiàn)。

成都創(chuàng)新互聯(lián)公司成都網(wǎng)站建設(shè)按需搭建網(wǎng)站,是成都網(wǎng)站設(shè)計(jì)公司,為輕質(zhì)隔墻板提供網(wǎng)站建設(shè)服務(wù),有成熟的網(wǎng)站定制合作流程,提供網(wǎng)站定制設(shè)計(jì)服務(wù):原型圖制作、網(wǎng)站創(chuàng)意設(shè)計(jì)、前端HTML5制作、后臺(tái)程序開發(fā)等。成都網(wǎng)站建設(shè)熱線:028-86922220
1、counter 實(shí)現(xiàn)了 + 和 - 運(yùn)算符用來合并記錄,還有像 most_common([n]) 這類很有用的方法。most_common([n]) 會(huì)按照次序返回映射里最常見的 n 個(gè)鍵和它們的計(jì)數(shù)。
In [1]: from collections import Counter
In [2]: langs = ['java', 'php', 'python', 'C#', 'kotlin', 'swift', 'python']
In [3]: ct = Counter(langs)
In [4]: ct
Out[4]: Counter({'C#': 1, 'java': 1, 'kotlin': 1, 'php': 1, 'python': 2, 'swift': 1})
In [5]: ct.update(['java', 'c'])
In [6]: ct
Out[6]:
Counter({'C#': 1,
'c': 1,
'java': 2,
'kotlin': 1,
'php': 1,
'python': 2,
'swift': 1})
In [7]: ct.most_common(2)
Out[7]: [('java', 2), ('python', 2)]2、直接操作字符串
In [9]: ct = Counter('abracadabra')
In [10]: ct
Out[10]: Counter({'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2})
In [11]: ct.update('aaaaazzz')
In [12]: ct
Out[12]: Counter({'a': 10, 'b': 2, 'c': 1, 'd': 1, 'r': 2, 'z': 3})
In [13]: ct.most_common(2)
Out[13]: [('a', 10), ('z', 3)]以上就是Counter在python中兩種用法,希望能對(duì)大家有所幫助,更多知識(shí)盡在python學(xué)習(xí)網(wǎng)。
新聞標(biāo)題:創(chuàng)新互聯(lián)Python教程:Counter在python中兩種用法
轉(zhuǎn)載源于:http://m.fisionsoft.com.cn/article/djsigds.html


咨詢
建站咨詢
