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

    Join Date
    Oct 2012
    Posts
    44
    Rep Power
    3

    Lists and element occurrance


    Hi,

    So i was wondering.. what if you have and output like..
    >>>
    a
    b
    b
    b
    d

    and you append it to make it [a,b,b,b,d]

    but then how would you get the number of times each element appears.. like basically replacing the string with int.

    for example:

    [1, 3, 1] <-- Something like this..

    Thank you
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    439
    Rep Power
    67
    Originally Posted by emo.vs.elmo
    and you append it to make it [a,b,b,b,d]

    but then how would you get the number of times each element appears.. like basically replacing the string with int.

    for example:

    [1, 3, 1] <-- Something like this..
    Assuming the list is sorted the following works in simple cases:

    Code:
    >>> l = ['a', 'b', 'b', 'b', 'd']
    >>> [l.count(elem) for elem in set(l)]
    [1, 3, 1]
    However, changing a list into a set might not retain the order of the elements.

    So to be on the safe side, you should use a dictionary instead.

    Code:
    >>> d = {}
    >>> for elem in l:
    	if elem in d:
    		d[elem] += 1
    	else:
    		d[elem] = 1
    
    		
    >>> d
    {'a': 1, 'b': 3, 'd': 1}
    My armada: openSUSE 13.2 (home desktop, work desktop), openSUSE 13.1 (home laptop), Debian GNU/Linux 7.7.0 (mini laptop), Ubuntu 14.04 LTS (server), Android 4.2.1 (tablet), Windows 7 Ultimate (testbed)
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    44
    Rep Power
    3
    but i want it to return a list.

    A set would be easier , and so is the dictionary.. but in this case returning a list is what i need to do.

    Thanks for helping though... i kinda understand the concept a little better
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    439
    Rep Power
    67
    Originally Posted by emo.vs.elmo
    but i want it to return a list.
    Look closer at what I wrote (the first alternative): the result is a list.
    My armada: openSUSE 13.2 (home desktop, work desktop), openSUSE 13.1 (home laptop), Debian GNU/Linux 7.7.0 (mini laptop), Ubuntu 14.04 LTS (server), Android 4.2.1 (tablet), Windows 7 Ultimate (testbed)
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    44
    Rep Power
    3
    I did do that, but count is not returning integers for some reason. Isn't there something non built in that would return the occurrence of each element? thanks

IMN logo majestic logo threadwatch logo seochat tools logo