Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use Python to implement counter Counter

Shulou Source: shulou.com Published: 2022-06-01 07:09:09 09月18日 Update

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:

Tags: Elements articles words counters content objects times references statistics highest concise elegant not so much author keywords parameters multiple most subclasses Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Xiaomi Huawei vpn MySQL