Get the App
SLTechnology News&Howtos  ›  Development  › 

How python finds the most frequently occurring elements in iterable objects

Shulou Source: shulou.com Published: 2022-06-01 05:41:10 10月04日 Update

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!

Tags: Elements articles frequent objects iterations dictionaries more ordinary necessary value tasks interests subtraction addition just at the same time examples in fact often see Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Microsoft MariaDB Xiaomi Docker