How to use Python to implement counter Counter
Editor to share with you how to use Python to achieve counter Counter, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Before you learn about Counter, consider a question. There is now a list of multiple words:
List1 = ['red','green','red','blue','green','red']
How to count the number of words in the list?
If you go a little deeper, how to count the number of words used by the author in a novel?
Python provides an elegant and concise solution: Counter
> from collections import Counter > Counter ('adffdsads') Counter ({' dudes: 3, 'fags: 2,' slots: 2, 'asides: 2})
Initialize the mapping object
> Counter ({'red':1,'green':2})
Counter ({'green': 2,' red': 1})
Initialize keyword parameter object
> Counter (cats=4,dogs=8)
Counter ({'dogs': 8,' cats': 4})
Counter is a subclass of dict, so you can safely use it like dict. For details, please refer to the dictionary [Python lesson 37].
Here's a common way to use Counter: