Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to implement counter Counter

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

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:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report