Counter class
The purpose of the Counter class is to keep track of the number of times a value occurs. It is an unordered container type stored as a dictionary of key-value pairs, where the element serves as the key and its count serves as the value.The count value can be any interger (including 0 and negative numbers).The Counter class is very similar to bags or multisets in other languages.
establish
Counter is a container object, the main role is used to count the hash object, you can use three ways to initialize the
- Parameter inside parameter iterable object Counter("success")
- Pass keyword argument Counter((s=3,c=2,e=1,u=1))
- Pass in the dictionary Counter({"s":3, "c"=2, "e"=1, "u"=1})
The following code illustrates the methods created by the Counter class:
>>> c = Counter() # Create an empty Counter class >>> c = Counter('gallahad') # Create from an iterable object (list, tuple, dict, string, etc.) >>> c = Counter({'a': 4, 'b': 2}) # Create from a dictionary object >>> c = Counter(a=4, b=2) # Creating a key-value pair from a set of
Count value access with missing keys
Returns 0 instead of KeyError when the key accessed does not exist; otherwise returns its count.
>>> c = Counter("abcdefgab") >>> c["a"] > 2 >>> c["c"] > 1 >>> c["h"] > 0
Counter update
You can use an iterable object or another Counter object to update the key value.
Counter updates include both increases and decreases.
Add the use of the update() method:
>>> c = Counter('which') >>> ('witch') # Use another iterable object to update >>> c['h'] > 2 >>> d = Counter('watch') >>> (d) # Use another Counter object to update >>> c['h'] > 3
To reduce, use the subtract() method:
>>> c = Counter('which') >>> ('witch') # Use another iterable object to update >>> c['h'] > 1 >>> d = Counter('watch') >>> (d) # Use another Counter object to update >>> c['a'] > -1
Deletion of keys
When the count value is 0, it does not mean that the element is deleted, and del should be used to delete the element.
>>> c = Counter("abcdcba") >>> c Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1}) >>> c["b"] = 0 >>> c Counter({'a': 2, 'c': 2, 'd': 1, 'b': 0}) >>> del c["a"] >>> c Counter({'c': 2, 'b': 2, 'd': 1})
elements()
Returns an iterator.
An element is repeated as many times as there are elements in the iterator. Elements are listed in no particular order, and elements with a number less than 1 are not included.
>>> c = Counter(a=4, b=2, c=0, d=-2) >>> list(()) ['a', 'a', 'a', 'a', 'b', 'b']
most_common([n])
Returns a TopN list. If n is not specified, all elements are returned. When multiple elements have the same count value, the ordering is nondeterministic.
>>> c = Counter('abracadabra') >>> c.most_common() [('a', 5), ('r', 2), ('b', 2), ('c', 1), ('d', 1)] >>> c.most_common(3) [('a', 5), ('r', 2), ('b', 2)]
fromkeys
Unimplemented class methods.
Shallow copy copy
>>> c = Counter("abcdcba") >>> c Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1}) >>> d = () >>> d Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})
Arithmetic and set operations
The +, -, &, | operations can also be used for Counter, where the & and | operations return the minimum and maximum values of the elements of the two Counter objects, respectively. Note that the resulting Counter object will remove elements less than 1.
>>> c = Counter(a=3, b=1) >>> d = Counter(a=1, b=2) >>> c + d # c[x] + d[x] Counter({'a': 4, 'b': 3}) >>> c - d # subtract (keep only elements with positive counts) Counter({'a': 2}) >>> c & d # Intersection: min(c[x], d[x]) Counter({'a': 1, 'b': 1}) >>> c | d # Concatenate: max(c[x], d[x]) Counter({'a': 3, 'b': 2})
Common Operations
Here are some common operations of the Counter class, from the official Python documentation.
sum(()) # Total of all counts () # Reset the Counter object, note that it is not deleted list(c) # Convert keys in c to lists set(c) # Convert keys in c to set dict(c) # Convert key-value pairs in c to dictionaries () # List in (elem, cnt) format Counter(dict(list_of_pairs)) # Convert from a (elem, cnt)-formatted list to a Counter class object c.most_common()[:-n:-1] # Take out the n elements with the lowest count c += Counter() # Remove 0 and negative values
to this article on the specific use of Python () article is introduced to this, more related Python () content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!