Counting by partial string in Python

Viewed 63

So, I have a list of strings (upper case letters).

list = ['DOG01', 'CAT02',  'HORSE04',  'DOG02',  'HORSE01', 'CAT01', 'CAT03',  'HORSE03',  'HORSE02']

How can I group and count occurrence in the list?
Expected output:

Expected output:

2 Answers

You may try using the Counter library here:

from collections import Counter
import re

list = ['DOG01', 'CAT02', 'HORSE04', 'DOG02', 'HORSE01', 'CAT01', 'CAT03', 'HORSE03', 'HORSE02']
list = [re.sub(r'\d+$', '', x) for x in list]
print(Counter(list))

This prints:

Counter({'HORSE': 4, 'CAT': 3, 'DOG': 2})

Note that the above approach simply strips off the number endings of each list element, then does an aggregation on the alpha names only.

you can also use dictionary

list= ['DOG01', 'CAT02',  'HORSE04',  'DOG02',  'HORSE01', 
      'CAT01', 'CAT03',  'HORSE03',  'HORSE02']
dic={}
for i in list:
    i=i[:-2]
    if i in dic:
        dic[i]=dic[i]+1
    else:
        dic[i]=1
print(dic)
Related