Counting number of each item in a list.
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Sun Mar 19 12:22:19 EST 2006
With CPython this is probably the faster version, the version with
list.count() has to be used only if you are sure to always have a short
input list, because it's O(n^2):
str_list = ['StringA', 'StringC', 'StringB',
'StringA', 'StringC', 'StringD',
'StringA' ]
str_counts = {}
for s in str_list:
if s in str_counts:
str_counts[s] += 1
else:
str_counts[s] = 1
Bye,
bearophile
More information about the Python-list
mailing list