Natrocks
Natrocks

Reputation: 114

Way to loop over Counter by number of times present?

I am using collections.Counter and I am trying to loop over the elements. However if I have t=Counter("AbaCaBA") and use a for loop to print each element, it would only print one of each letter:

   for i in t:
       print(i)

would print:

    a
    C
    A
    b
    B

How would I loop over it in a way that would print as many of each letter as there are? As in, 2 A's, 2 a's, 1 b, 1 B, 1 C.

Edit: apparently there is a method called elements() that serves this exact purpose.

Upvotes: 0

Views: 265

Answers (2)

Natrocks
Natrocks

Reputation: 114

Discovered the elements() method shortly after posting this, here: https://docs.python.org/3/library/collections.html#collections.Counter

It returns an iterator that repeats each element as many times as it is counted, ignoring elements with counts<1

    for i in t.elements():
         print(i)

Upvotes: 1

Davis Yoshida
Davis Yoshida

Reputation: 1787

When you iterate over a Counter you are iterating over the keys. In order to get the counts at the same time you could do something like:

for i, count in t.items():
    print('{} {}s'.format(count, i))

Upvotes: 1

Related Questions