TIL: Python's collections.Counter makes frequency counting trivial
As developers, we often find ourselves needing to count the frequency of elements in a list or other iterable. I recently stumbled upon Python's collections.Counter class, which makes this task incredibly simple.
Let's compare the traditional approach with the Counter class. Here's an example of how you might count frequencies manually:
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
frequency = {}
for fruit in fruits:
if fruit in frequency:
frequency[fruit] += 1
else:
frequency[fruit] = 1
And here's the equivalent using Counter:
Follow me on Dev.to for daily Python tips and quick guides!
If you found this useful, you might like Python Automation Scripts Pack (10 Ready-to-Use Tools) — a practical resource that takes things a step further. At $14.99 it's a solid investment for your toolkit.
喜欢这篇文章?关注获取更多Python自动化内容!
Top comments (0)