Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting equal strings in Python

I have a list of strings and some of them are equal. I need some script which would count equal strings. Ex:

I have a list with some words :

"House"
"Dream"
"Tree"
"Tree"
"House"
"Sky"
"House"

And the output should look like this:

"House" - 3
"Tree" - 2
"Dream" - 1
and so on

like image 593
4lex1v Avatar asked Dec 02 '22 00:12

4lex1v


1 Answers

Use collections.Counter(). It is designed for exactly this use case:

>>> import collections
>>> seq = ["House", "Dream", "Tree", "Tree", "House", "Sky", "House"]
>>> for word, cnt in collections.Counter(seq).most_common():
        print repr(word), '-', cnt

'House' - 3
'Tree' - 2
'Sky' - 1
'Dream' - 1
like image 163
Raymond Hettinger Avatar answered Dec 14 '22 22:12

Raymond Hettinger