1.创建
class Counter(dict): 字典的一个子类 >>> import collections >>> obj = collections.Counter(‘sdfsdsdffgscvsd‘) >>> print(obj) Counter({‘s‘: 5, ‘d‘: 4, ‘f‘: 3, ‘c‘: 1, ‘g‘: 1, ‘v‘: 1}) >>> obj = collections.Counter([‘11‘,‘22‘,‘33‘,‘44‘]) >>> print(obj) Counter({‘22‘: 1, ‘44‘: 1, ‘11‘: 1, ‘33‘: 1}) >>>
2.most_common
>>> obj = collections.Counter(‘sdfsdsdffgscvsd‘) >>> print(obj.most_common(2)) [(‘s‘, 5), (‘d‘, 4)]
3.循环
>>> obj = collections.Counter(‘sdfsdsdffgscvsd‘) >>> for k,v in obj.items(): ... print(k,v) ... c 1 f 3 g 1 d 4 s 5 v 1
4.elements
>>> for item in obj.elements(): ... print(item) ... c f f f g d d d d s s s s s v >>> obj = collections.Counter([‘11‘,‘22‘,‘33‘,‘44‘]) >>> for item in obj.elements(): ... print(item) ... 22 44 11 33
5.update
>>> obj = collections.Counter([‘11‘,‘22‘,‘33‘,‘44‘]) >>> obj.update([‘33‘,‘44‘,‘55‘]) >>> print(obj) Counter({‘44‘: 2, ‘33‘: 2, ‘55‘: 1, ‘22‘: 1, ‘11‘: 1}) >>>
6.相减
>>> obj = collections.Counter([‘11‘,‘22‘,‘33‘,‘44‘]) >>> obj.subtract([‘33‘,‘33‘,‘55‘]) >>> print(obj) Counter({‘22‘: 1, ‘44‘: 1, ‘11‘: 1, ‘55‘: -1, ‘33‘: -1}) >>>
时间: 2024-12-27 12:50:36