Get the App
SLTechnology News&Howtos  ›  Development  › 

How does python count hashable objects with collections.Counter

Shulou Source: shulou.com Published: 2022-06-01 05:15:35 09月28日 Update

Editor to share with you how python uses collections.Counter to count hashable objects. I hope you will get something after reading this article. Let's discuss it together.

Count hashable objects with collections.Counter

If we need to count the number of elements in the list, there is a very convenient tool in the collections module that can do this. We just need to import counters from the collection and create counter objects with lists as parameters. If we print this, then for each item in the list, we can see the number of times this item appears, and it is sorted, with the most commonly used items first. It would be much better to calculate alone. If we want to get a count of an item, simply visit the item and it will return the corresponding count. If the item is not included, 0 is returned.

From collections import Counter my_list = [10, 10, 10, 5, 5, 2, 9, 9, 9, 9, 9, 9, 9, 9] counter = Counter (my_list) print (counter) # Counter ({9: 6, 10: 3, 5: 2, 2: 1}) print (counter [10]) # 3 after reading this article, I believe you have some understanding of "how python counts hashable objects with collections.Counter". If you want to know more about it. Welcome to follow the industry information channel, thank you for reading!

Tags: Objects articles counters elements parameters just done tools commonly used quantity more modules times knowledge industry information information channels channels guides good Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Tech Info NVidia Shulou Technology Linux