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

    Join Date
    Apr 2004
    Posts
    57
    Rep Power
    11

    how to count chars in list


    Hi all

    list [ abcttraadezzreyeuw]
    now how can i count the number of each characters
    ie.. 3a's 2t's and on

    Thanks
  2. #2
  3. A wanna-be guru of some sort
    Devshed Novice (500 - 999 posts)

    Join Date
    Sep 2004
    Location
    Either online or offline
    Posts
    625
    Rep Power
    19
    First off, the list should be

    list = ['a', 'b', 'c', ...]
    to be a list of characters. What you wrote down, the interpreter understands as a variable as index to the list, and since you did not declare it, it won't work.

    You could have another list containing all letters, and then dynamically compare two lists to see which and how many of the elements in list 1 match the letters of the alphabet in list 2.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    Houston, TX
    Posts
    383
    Rep Power
    13
    So is this a list of individual characters or a string or a list of strings?

    The basic code is:
    Code:
    L = ['a', 'bc', 'def', 'aa', 'bcbc']
    s = ''.join(L)
    charFreqs = {}
    for char in s:
        if char in charFreqs:
            charFreqs[char] += 1
        else:
            charFreqs[char] = 1
    Debian - because life's too short for worrying.
    Best. (Python.) IRC bot. ever.
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Another simple solution, this time using the count() method.

    Code:
    >>> sequence = 'Hello again lucky!'
    >>> 
    >>> counters = {}
    >>> 
    >>> for character in sequence:
    ...     if character not in counters:
    ...         counters[character] = sequence.count(character)
    ... 
    >>> counters
    {'a': 2, ' ': 2, 'c': 1, 'e': 1, 'g': 1, 'i': 1, 'H': 1, 'k': 1, 'l': 3, 'o': 1, 'n': 1, '!': 1, 'u': 1, 'y': 1}
    >>>
    In the example sequence is a string, but since Python treats iteration over Strings, Lists and Tuples in same way it "shouldn't" matter which data-type is used here.

    However, Tuples don't have a count() method, which limits you to using either a String or a List if you want to do it this way .

    Take care,

    Mark.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo