Python_collections_Counter计数器部分功能介绍
counter():是对字典的补充,用来方便的计数,继承了字典
import collections obj = collections.Counter('yigbavfsdcfdsfdsd') print(obj)
结果: Counter({'d': 4, 'f': 3, 's': 3, 'y': 1, 'i': 1, 'g': 1, 'b': 1, 'a': 1, 'v': 1, 'c': 1})
x.most_common():按照counter计数,以列表的形式降序返回前n项元素
import collections obj = collections.Counter('yigbavfsdcfdsfdsd') print(obj) print(obj.most_common(4))
结果: Counter({'d': 4, 'f': 3, 's': 3, 'y': 1, 'i': 1, 'g': 1, 'b': 1, 'a': 1, 'v': 1, 'c': 1}) [('d', 4), ('f', 3), ('s', 3), ('y', 1)]
x.element():按照Counter的计数返回元素
import collections obj = collections.Counter('yigbavfsdcfdsfdsd') for k in obj.elements(): print(k)
结果:
y
i
g
b
a
v
f
f
f
s
s
s
d
d
d
d
c
x.update():更新计数器,在原来的基础上增加或者修改
x.subtract():在原计数器的基础上减少元素,没有的记为负
import collections obj = collections.Counter(['33', 'we', '33', '11']) print(obj) obj.update(['zhao', '11', 'qq', '11', ]) print(obj) obj.subtract(['zhao', '11', 'qq', 'lihao', ]) print(obj)
结果:
Counter({'33': 2, 'we': 1, '11': 1})
Counter({'11': 3, '33': 2, 'we': 1, 'zhao': 1, 'qq': 1})
Counter({'33': 2, '11': 2, 'we': 1, 'zhao': 0, 'qq': 0, 'lihao': -1})