簡單掌握Python的Collections模塊中counter結構的用法

分類:IT技術 時間:2016-10-11

counter 是一種特殊的字典,主要方便用來計數,key 是要計數的 item,value 保存的是個數。

from collections import Counter

>>> c = Counter('hello,world')
Counter({'l': 3, 'o': 2, 'e': 1, 'd': 1, 'h': 1, ',': 1, 'r': 1, 'w': 1})

初始化可以傳入三種類型的參數:字典,其他 iterable 的數據類型,還有命名的參數對。

 | __init__(self, iterable=None, **kwds)
 |  Create a new, empty Counter object. And if given, count elements
 |  from an input iterable. Or, initialize the count from another mapping
 |  of elements to their counts.
 |
 |  >>> c = Counter()       # a new, empty counter
 |  >>> c = Counter('gallahad')     # a new counter from an iterable
 |  >>> c = Counter({'a': 4, 'b': 2})   # a new counter from a mapping
 |  >>> c = Counter(a=4, b=2)     # a new counter from keyword args

默認請求下,訪問不存在的 item,會返回 0。Counter 可以用來統計某些數據的出現次數,比如一個很長的數字串 numbers = "67642192097348921647512014651027586741512651" 中每個數字的頻率:

>>> c = Counter(numbers) # c 存儲了每個數字的頻率
>>> c.most_common()  # 所有數字按照頻率排序。如果 most_common 接受了 int 參數 n,將返回頻率前n 的數據,否則會返回所有的數據
[('1', 8),
 ('2', 6),
 ('6', 6),
 ('5', 5),
 ('4', 5),
 ('7', 5),
 ('0', 3),
 ('9', 3),
 ('8', 2),
 ('3', 1)]

此外,你還可以對兩個 Counter 對象進行 +, -,min, max 等操作。

綜合示例:

print('Counter類型的應用') 
c = Counter("dengjingdong") 
#c = Counter({'n': 3, 'g': 3, 'd': 2, 'i': 1, 'o': 1, 'e': 1, 'j': 1}) 
print("原始數據:",c) 
print("最多的兩個元素:",c.most_common(2))#輸出數量最多的元素 
print("d的個數:",c['d'])#輸出d的個數 
print(c.values())#輸出字典的value列表 
print(sum(c.values()))#輸出總字符數 
print(sorted(c.elements()))#將字典中的數據,按字典序排序 
print('\n\n') 
""" 
#刪除所有d元素 
del c['d'] 
b = Counter("dengxiaoxiao") 
#通過subtract函數刪除元素,元素個數可以變成負數。 
c.subtract(b) 
""" 
 
""" 
可以添加數據 
b = Counter("qinghuabeida") 
c.update(b) 
""" 


Tags: elements counter keyword another numbers

文章來源:


ads
ads

相關文章
ads

相關文章

ad