By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,806 Members | 1,327 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,806 IT Pros & Developers. It's quick & easy.

Python program that counts the occurance of values in a set of data.

P: 2
Hello All. I was curious if someone is willing to show me how I could write a simple python program that counts the number of times a value appears in a data list ( data that I have already written this to another file).

Much Thanks.
Jul 28 '08 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 2.5K+
P: 2,851
List method count() returns the number of times a value or object occurs in a list.
Expand|Select|Wrap|Line Numbers
  1. >>> alist = [1,2,3,4,4,4]
  2. >>> alist.count(4)
  3. 3
  4. >>> 
Jul 28 '08 #2

P: 5
If you want to count all members of the list without specifying which one to count, you could use this reasonably standard count method (this is from the Natural Language Toolkit's online Python tutorial:

Expand|Select|Wrap|Line Numbers
  1. alist = [1,2,3,4,4,4]
  3. count = {}
  4. for thing in alist:        # iterates though each member of your list
  5.     if thing not in count: # checks to see if member already exists in the count
  6.         count[thing] = 0   # if a member has not been counted yet, start an entry for it                         
  7.     count[thing] += 1      # each time you see a member, add one to its count
  9. print count
Output = {1: 1, 2: 1, 3: 1, 4: 3}

This says "the number "1" was found once; the number "2" was found once; the number 3 was found once; the number "4" was found three times.
Jul 31 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.