Natrocks Natrocks - 2 months ago 8
Python Question

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.

Answer

A Counter is an unordered collection, so once your letters are in there, you won't be able to print them out in the same order you inserted them.

If that doesn't matter to you, then iterate through the items() and use range to print them out count number of times, like this:

for letter, count in t.items():
    for num in range(1, count + 1):
        print(letter)

That will give you output similar to:

C
b
A
A
a
a
B