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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • masha2011
    New Member
    • Jul 2008
    • 2

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

    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.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    List method count() returns the number of times a value or object occurs in a list.[code=Python]>>> alist = [1,2,3,4,4,4]
    >>> alist.count(4)
    3
    >>> [/code]

    Comment

    • Slippy27
      New Member
      • May 2008
      • 5

      #3
      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: http://nltk.org/doc/en/programming.htm l)

      [code=Python]
      alist = [1,2,3,4,4,4]

      count = {}
      for thing in alist: # iterates though each member of your list
      if thing not in count: # checks to see if member already exists in the count
      count[thing] = 0 # if a member has not been counted yet, start an entry for it
      count[thing] += 1 # each time you see a member, add one to its count

      print count
      [/code]

      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.

      Comment

      Working...