Python Counter函数
生活随笔
收集整理的這篇文章主要介紹了
Python Counter函数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
> c = Counter() # 創(chuàng)建一個(gè)新的空counter
> c = Counter('abcasdf') # 一個(gè)迭代對象生成的counter
> c = Counter({'red': 4, 'yello': 2}) # 一個(gè)映射生成的counter
> c = Counter(cats=2, dogs=5) # 關(guān)鍵字參數(shù)生成的counter# counter 生成counter, 雖然這里并沒有什么用
> from collections import Counter
> c = Counter('abcasd')
> c
Counter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})
> c2 = Counter(c)
> c2
Counter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})
因?yàn)?Counter?實(shí)現(xiàn)了字典的?__missing__?方法, 所以當(dāng)訪問不存在的key的時(shí)候,返回值為0:
> c = Counter(['apple', 'pear']) > c['orange'] 0counter?常用的方法:
# elements() 按照counter的計(jì)數(shù),重復(fù)返回元素 > c = Counter(a=4, b=2, c=0, d=-2) > list(c.elements()) ['a', 'a', 'a', 'a', 'b', 'b']# most_common(n) 按照counter的計(jì)數(shù),按照降序,返回前n項(xiàng)組成的list; n忽略時(shí)返回全部 > Counter('abracadabra').most_common(3) [('a', 5), ('r', 2), ('b', 2)]# subtract([iterable-or-mapping]) counter按照相應(yīng)的元素,計(jì)數(shù)相減 > c = Counter(a=4, b=2, c=0, d=-2) > d = Counter(a=1, b=2, c=3, d=4) > c.subtract(d) > c Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})# update([iterable-or-mapping]) 不同于字典的update方法,這里更新counter時(shí),相同的key的value值相加而不是覆蓋 # 實(shí)例化 Counter 時(shí), 實(shí)際也是調(diào)用這個(gè)方法# Counter 間的數(shù)學(xué)集合操作 > c = Counter(a=3, b=1, c=5) > d = Counter(a=1, b=2, d=4) > c + d # counter相加, 相同的key的value相加 Counter({'c': 5, 'a': 4, 'd': 4, 'b': 3}) > c - d # counter相減, 相同的key的value相減,只保留正值得value Counter({'c': 5, 'a': 2}) > c & d # 交集: 取兩者都有的key,value取小的那一個(gè) Counter({'a': 1, 'b': 1}) > c | d # 并集: 匯聚所有的key, key相同的情況下,取大的value Counter({'c': 5, 'd': 4, 'a': 3, 'b': 2})常見做法: sum(c.values()) # 繼承自字典的.values()方法返回values的列表,再求和 c.clear() # 繼承自字典的.clear()方法,清空counter list(c) # 返回key組成的list set(c) # 返回key組成的set dict(c) # 轉(zhuǎn)化成字典 c.items() # 轉(zhuǎn)化成(元素,計(jì)數(shù)值)組成的列表 Counter(dict(list_of_pairs)) # 從(元素,計(jì)數(shù)值)組成的列表轉(zhuǎn)化成Counter c.most_common()[:-n-1:-1] # 最小n個(gè)計(jì)數(shù)的(元素,計(jì)數(shù)值)組成的列表 c += Counter() # 利用counter的相加來去除負(fù)值和0的值總結(jié)
以上是生活随笔為你收集整理的Python Counter函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL中EXPLAIN解析
- 下一篇: python 微信分享链接_python