代码
import collections#counter继承字典的方法,items(),keys(),vavle()
obj = collections.Counter('acbdafcbad')
print(obj)
print(type(obj))
print(obj.most_common(3))
for item in obj.elements():
print(item)
for k,v in obj.items():
print(k,v)
obj.update(['a','b','b','w','c'])#加元素
print(obj)
obj.subtract(['w','c','z'])#减元素
print(obj)
结果:
Counter({'a': 3, 'b': 2, 'd': 2, 'c': 2, 'f': 1})
<class 'collections.Counter'>
[('a', 3), ('b', 2), ('d', 2)]
a
a
a
b
b
d
d
c
c
f
a 3
b 2
d 2
c 2
f 1
Counter({'a': 4, 'b': 4, 'c': 3, 'd': 2, 'w': 1, 'f': 1})
Counter({'a': 4, 'b': 4, 'd': 2, 'c': 2, 'f': 1, 'w': 0, 'z': -1})