2

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 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.