【轉】python Counter模塊
阿新 • • 發佈:2018-09-20
沒有 count iter pytho 創建 list div mapping app
>>> 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‘] 0
counter
常用的方法:
# 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模塊