Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a builtin method similar to Counter in Python?

Tags:

raku

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;

like image 959
Stats4224 Avatar asked Jul 23 '18 17:07

Stats4224


People also ask

Does Python have a counter?

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.

What library is counter in Python?

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.

Where is counter in Python?

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.


1 Answers

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
like image 145
Elizabeth Mattijsen Avatar answered Nov 26 '22 22:11

Elizabeth Mattijsen