Specific use of collections. Counter of in Python

  • 2021-11-14 06:24:25
  • OfStack

Directory Counter class
Create
Count Value Access and Missing Key
Update of counters
Deletion of key
elements()
most_common([n])
fromkeys
Shallow copy copy
Arithmetic and set operations
Common operations

Class Counter

The purpose of the Counter class is to keep track of the number of occurrences of a value. It is an unordered container type stored as a dictionary key-value pair with elements as key and counts as value. The count value can be any Interger (including 0 and negative). The Counter class is similar to bags or multisets in other languages.

Create

Counter is a container object, which is mainly used to count hash objects. It can be initialized in three ways

Parameters can iterate the object Counter ("success") Pass in the keyword parameter Counter ((s=3, c=2, e=1, u=1)) Passed into the dictionary Counter ({"s": 3, "c" = 2, "e" = 1, "u" = 1})

The following code illustrates the method created by the Counter class:


>>> c = Counter()  #  Create 1 Empty Counter Class 
>>> c = Counter('gallahad')  #  From 1 A can iterable Object ( list , tuple , dict , string, and so on 
>>> c = Counter({'a': 4, 'b': 2})  #  From 1 Creation of dictionary objects 
>>> c = Counter(a=4, b=2)  #  From 1 Group key-value pair creation 

Count Value Access and Missing Key

Returns 0 instead of KeyError when the accessed key does not exist; Otherwise, its count is returned.


>>> c = Counter("abcdefgab")
>>> c["a"]
> 2
>>> c["c"]
> 1
>>> c["h"]
> 0

Update of counters

You can use one iterable object or another Counter object to update the key value.

Counter updates include increment and decrease.

Increase the use of update () method:


>>> c = Counter('which')
>>> c.update('witch')  #  Use another 1 A iterable Object update 
>>> c['h']
> 2
>>> d = Counter('watch')
>>> c.update(d)  #  Use another 1 A Counter Object update 
>>> c['h']
> 3

To decrease, use the subtract () method:


>>> c = Counter('which')
>>> c.subtract('witch')  #  Use another 1 A iterable Object update 
>>> c['h']
> 1
>>> d = Counter('watch')
>>> c.subtract(d)  #  Use another 1 A Counter Object update 
>>> c['a']
> -1

Deletion of key

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 1 iterator.

Elements are contained in the iterator as many times as they are repeated. Elements are arranged in no definite order, and elements with a number less than 1 are not included.


>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

most_common([n])

Returns 1 TopN list. If n is not specified, all elements are returned. When the count values of multiple elements are the same, the arrangement is in no definite order.


>>> 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 method.

Shallow copy copy


>>> c = Counter("abcdcba")
>>> c
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})
>>> d = c.copy()
>>> d
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})

Arithmetic and set operations

+,-, & The operation can also be used for Counter. Among them & The and operations return the minimum and maximum values of each element of the two Counter objects, respectively. Note that the resulting Counter object deletes 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 (Only positive count elements are retained) 
Counter({'a': 2})
>>> c & d  #  Intersection :  min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d  #  Union :  max(c[x], d[x])
Counter({'a': 3, 'b': 2})
 

Common operations

The following are some common operations of Counter class, which are derived from Python official documents.


sum(c.values())  #  Total of all counts 
c.clear()  #  Reset Counter Object, note that it is not deleted 
list(c)  #  Will c Turn the keys in the list 
set(c)  #  Will c Convert the key in the set
dict(c)  #  Will c Convert key-value pairs in to dictionaries 
c.items()  #  Convert to (elem, cnt) Format list 
Counter(dict(list_of_pairs))  #  From (elem, cnt) Format list is converted to Counter Class object 
c.most_common()[:-n:-1]  #  Take out the least counted n Elements 
c += Counter()  #  Remove 0 And negative values 

Related articles: