I've dug through the docs, but I can't seem to find anything similar to the Counter in Python.
I know I can write something similar trivially, but a builtin would be so convenient.
Trivial example:
my %h; %h{$_}++ for @test;
Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.
A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.
The counter is a sub-class available inside the dictionary class. The counter is a sub-class available inside the dictionary class. Using the Python Counter tool, you can count the key-value pairs in an object, also called a hash table object.
The Bag class does what you want.
my %h is Bag = @test;
Or if you just want to coerce:
my $bag = @test.Bag;
In either case, you can use the object like any ordinary Hash
.
# show sorted with most frequent first
say "{.key} seen {.value} times" for %h.sort: -*.value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With