Python--Counter class
I know you'll come, so I'll wait
Reference
Official documents
Class collections. Counter ([iterable-or-mapping])
Counter is integrated into the Dict class, so you can also use the dictionary method, which returns a collection of Counter objects with element key and number of elements as value
>>> from collections import Counter>>> s = "hello pinsily">>> d = Counter(s)>>> dCounter({‘l‘: 3, ‘i‘: 2, ‘h‘: 1, ‘e‘: 1, ‘o‘: 1, ‘ ‘: 1, ‘p‘: 1, ‘n‘: 1, ‘s‘: 1, ‘y‘: 1})
Elements ()
Returns an iterator
>>> d.elements()<itertools.chain object at 0x0000019AC812BBA8># 可以进行打印和排序>>> for i in d.elements():... print(i)...
Most_common (N)
Returns the highest number of first n elements
>>> d.most_common(3)[(‘l‘, 3), (‘i‘, 2), (‘h‘, 1)]
Subtract ([iterable-or-mapping])
Equivalent to subtraction, Counter that call this method will be overwritten.
>>> c = Counter(a=4, b=2, c=0, d=-2)>>> d = Counter(a=1, b=2, c=3, d=4)>>> c.subtract(d)>>> cCounter({‘a‘: 3, ‘b‘: 0, ‘c‘: -3, ‘d‘: -6})>>> dCounter({‘d‘: 4, ‘c‘: 3, ‘b‘: 2, ‘a‘: 1})
Summarize
When you need to count a large amount of data in a list, you can use Counter directly instead of creating a new dictionary to count
Python--Counter class