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 python finds the most frequently occurring elements in iterable objects

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces python how to find the most frequently occurring elements in iterable objects, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.

Find the elements that occur most frequently in iterable objects

Finding the most common elements in the list is a very common task. You can use for loops and dictionaries (map), but this is not necessary because there are Counter classes in the collections module:

From collections import Counter cheese = ["gouda", "brie", "feta", "cream cheese", "feta", "cheddar", "parmesan", "parmesan", "cheddar", "mozzarella", "cheddar", "gouda", "parmesan", "camembert", "emmental", "camembert" "parmesan"] cheese_count = Counter (cheese) print (cheese_count.most_common (3)) # Prints: [('parmesan', 4), (' cheddar', 3), ('gouda', 2)]

In fact, Counter is just a dictionary that maps elements to the number of occurrences, so you can use it as a normal dictionary:

Python print (cheese_count ["mozzarella"]) K40K cheese_count ["mozzarella"] + = 1 print (cheese_count ["mozzarella"]) K41K

In addition, you can easily add more elements using the update (more_words) method. Another cool feature of Counter is that you can use mathematical operations (addition and subtraction) to combine and subtract Counter instances.

Thank you for reading this article carefully. I hope the article "python how to find the most frequently occurring elements in iterable objects" shared by the editor will be helpful to you. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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

Development

Wechat

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

12
Report