collections模块中有一个叫做Counter的类,该类的作用就是计数器,Counter是对dict的加工,所有Counter继承了dict的方法
1、创建一个Counter,需要import collections库,通过collections库创建Counter,主要的功能就是统计每个元素出现的次数
import collections obj = collections.Counter("adalfjklajflkajfklejlasdkfjaklfjlkasfja") print(obj) # Counter({'a': 8, 'l': 7, 'j': 7, 'f': 6, 'k': 6, 'd': 2, 's': 2, 'e': 1})
l1 = ["ada","ada","cc"]
obj = collections.Counter(l1)
print(obj)
# Counter({'ada': 2, 'cc': 1})
2、Counter的另外一个方法就是most_common,可以指定统计出出现次数排名前X的元素,出现的次数从大到小排列,比如下面的例子,只统计出现次数最多的前3个元素
obj = collections.Counter("adalfjklajflkajfklejlasdkfjaklfjlkasfja") print(obj) ret = obj.most_common(3) print(ret) # [('a', 8), ('l', 7), ('j', 7)]
3、elements方法,可以列出Counter对象中的每一个元素
l1 = ["ada","ada","cc"] obj = collections.Counter(l1) print(obj) for i in obj.elements(): print(i) # ada # ada # cc
4、update方法,可以增加Counter对象中的内容
l1 = ["ada","ada","cc"] obj = collections.Counter(l1) print(obj) # Counter({'ada': 2, 'cc': 1}) l2 =["cc","add","ada",1] obj.update(l2) print(obj) # Counter({'ada': 3, 'cc': 2, 'add': 1, 1: 1})
5、subtract方法,可以减少Counter对象中的内容,可以看到如果减少的元素在Counter中没有,则该元素的值为-1
l1 = ["ada","ada","cc"] l2 =["cc","add","ada",1] obj = collections.Counter(l1) print(obj) # Counter({'ada': 2, 'cc': 1}) obj.subtract(l2) print(obj) # Counter({'ada': 1, 'cc': 0, 'add': -1, 1: -1})
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/20914.html