Counter (): is a dictionary supplement that is used to conveniently count and inherit the dictionary
Import= collections. Counter ('yigbavfsdcfdsfdsd')print(obj)
Result: Counter ({'D': 4,'F': 3,'s': 3,'y': 1,'I': 1,'g': 1,'b': 1,'a': 1,'v': 1,'C': 1})
X.most_common (): Returns the first n elements in descending order of the counter count, in the form of a list
Import= collections. Counter ('yigbavfsdcfdsfdsd')print(obj) Print(Obj.most_common (4))
Result: 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 (): Returns an element according to the count of counter
Import= collections. Counter ('yigbavfsdcfdsfdsd') for in Obj.elements (): print(k)
Results: YIGBAVFFFSSSDDDDC
X.update (): Update counter, add or modify on original basis
X.subtract (): Reduces the element on the basis of the original counter, and does not count as negative
ImportCollectionsobj= Collections. Counter ([' -','We',' -',' One'])Print(obj) obj.update (['Zhao',' One','QQ',' One', ])Print(obj) obj.subtract (['Zhao',' One','QQ','Lihao', ])Print(obj)
Results:
Counter ({' $ ': 2, ' we ': 1, ' 11 ': 1})
Counter ({' One ': 3, ' $ ': 2, ' we ': 1, ' Zhao ': 1, ' QQ ': 1})
Counter ({' $ ': 2, ' one ': 2, ' we ': 1, ' Zhao ': 0, ' QQ ': 0, ' Lihao ':-1})
Python_collections_counter Counter Section function introduction