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