#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    66
    Rep Power
    3

    Question about lists


    Hi, what could I do if I wanted to find out how many times a certain value appeared in a list. For example how could I find out how many times "Z" appeared in list 1

    thanks
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    San Francisco Bay
    Posts
    1,939
    Rep Power
    1313
    Code:
    >>> from collections import defaultdict
    >>> d = defaultdict(int)
    >>> a = ['a', 'b', 'c', 'a', 'b', 'd']
    >>> for x in a:
    ...     d[x] += 1
    ...     
    >>> d['a']
    2
    >>> d['b']
    2
    >>> d['c']
    1
    >>> d['d']
    1
    This counts the occurrences of every value in the list, assuming each value is hashable. If you only care about one value, I think you're better off manually comparing each list item to the value and incrementing a counter when equality occurs.
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,965
    Rep Power
    481
    I'd use the interpreter. Browsing through the output of

    >>> help(list())

    I'd find a count method. And then I'd learn more detail:

    >>> help(list().count)

    And maybe I'd look in the iterables or list section of the module library reference at docs.python.org .

    And I'd practice with a few cases back in the interpreter to make sure the funny variations I can think of work in reasonable ways.

    And then I'd be ready to use the list.count method.

    Comments on this post

    • Lux Perpetua agrees : This is certainly simpler than my methods.
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    66
    Rep Power
    3
    alright thanks
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Location
    Texas
    Posts
    24
    Rep Power
    0
    Here's an example of what b49P23TIvg was referring to:

    Code:
    >>> a=['A','B','A','C']
    >>> a.count('A')
    2
    >>> a.count('B')
    1
    >>> a.count('E')
    0
    >>> for i in range (0,a.count('A')):
    ...   e = a.index('A',i)
    ...   print ("element ",e," is the letter ",a[e])
    ...
    element  0  is the letter  A
    element  2  is the letter  A
    >>>

IMN logo majestic logo threadwatch logo seochat tools logo