Python Counter函数
生活随笔
收集整理的這篇文章主要介紹了
Python Counter函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
> c = Counter() # 創建一個新的空counter
> c = Counter('abcasdf') # 一個迭代對象生成的counter
> c = Counter({'red': 4, 'yello': 2}) # 一個映射生成的counter
> c = Counter(cats=2, dogs=5) # 關鍵字參數生成的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})
因為?Counter?實現了字典的?__missing__?方法, 所以當訪問不存在的key的時候,返回值為0:
> c = Counter(['apple', 'pear']) > c['orange'] 0counter?常用的方法:
# elements() 按照counter的計數,重復返回元素 > c = Counter(a=4, b=2, c=0, d=-2) > list(c.elements()) ['a', 'a', 'a', 'a', 'b', 'b']# most_common(n) 按照counter的計數,按照降序,返回前n項組成的list; n忽略時返回全部 > Counter('abracadabra').most_common(3) [('a', 5), ('r', 2), ('b', 2)]# subtract([iterable-or-mapping]) counter按照相應的元素,計數相減 > 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時,相同的key的value值相加而不是覆蓋 # 實例化 Counter 時, 實際也是調用這個方法# Counter 間的數學集合操作 > 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取小的那一個 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) # 轉化成字典 c.items() # 轉化成(元素,計數值)組成的列表 Counter(dict(list_of_pairs)) # 從(元素,計數值)組成的列表轉化成Counter c.most_common()[:-n-1:-1] # 最小n個計數的(元素,計數值)組成的列表 c += Counter() # 利用counter的相加來去除負值和0的值總結
以上是生活随笔為你收集整理的Python Counter函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL中EXPLAIN解析
- 下一篇: Windows基础篇学习(上)