import collections
obj = collections.Counter('Hi I am Python,I learn Python and I love Python')
print(obj)
# Counter({' ': 9, 'n': 5, 'o': 4, 'a': 3, 'h': 3, 't': 3, 'P': 3, 'I': 3, 'y': 3, 'e': 2, 'l': 2, 'i': 1, 'm': 1, 'r': 1, ',': 1, 'H': 1, 'v': 1, 'd': 1})
print(obj.most_common(4))
# [(' ', 9), ('n', 5), ('o', 4), ('P', 3)]
for i in obj.elements():
print(i,end=' ')
# e e t t t P P P r , I I I o o o o y y y H n n n n n h h h i l l v m a a a d 打印所有元素
print()
for item in obj.items():
print(item,end='*')
# ('r', 1)*(',', 1)*('y', 3)*('i', 1)*('h', 3)*(' ', 9)*('a', 3)*('o', 4)*('e', 2)*('l', 2)*('m', 1)*('P', 3)*('d', 1)*('H', 1)*('v', 1)*('t', 3)*('I', 3)*('n', 5)*
new = collections.Counter([11,12,12,13,13,13])
print(new)
# Counter({13: 3, 12: 2, 11: 1})
new.update([14,14,14,14])
print(new)
# Counter({14: 4, 13: 3, 12: 2, 11: 1})
new.subtract([11,11,12,12,12])
print(new)
# Counter({14: 4, 13: 3, 11: -1, 12: -1})
python collections Counter
最新推荐文章于 2024-11-27 09:50:54 发布