[Tutor] Counting help
Alan G
alan.gauld at freenet.co.uk
Tue Aug 23 21:55:56 CEST 2005
>I have extracted a list of names, i.e.
>
> "Joe Smith"
> "Joe Smith"
> "Jack Smith"
> "Sam Love"
> "Joe Smith"
>
> I need to be able to count the occurances of these names and I
> really don't have any idea where to begin.
The classic way to do this kind of thing is with a dictionary:
names = [
"Joe Smith",
"Joe Smith",
"Jack Smith",
"Sam Love",
"Joe Smith"]
counts = {}
for name in names:
if name in counts:
counts[name] += 1
else: counts[name] = 1
print counts
You could also use a list comprehension combined with the list
count() method but I doubt if its much faster.
HTH,
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list