Counting number of each item in a list.

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Mar 19 11:24:55 EST 2006


sophie_newbie a écrit :
> I have a list a little something like this:
> 
> StringA
> StringC
> StringB
> StringA
> StringC
> StringD
> StringA
> ...
> etc.
> 
> Basically I was wondering if there was an easy way to return how many
> of each string are in the list, something like this:
> 
> StringA - 3
> StringB - 1
> StringC - 2
> StringD - 1

There is.

str_list = ['StringA', 'StringC', 'StringB',
             'StringA', 'StringC', 'StringD',
             'StringA' ]

str_counts = dict((s, str_list.count(s) for s in set(str_list))




More information about the Python-list mailing list