Search code examples
pythonlistcountrangeprobability

how to count for a range of integers in a list


I am trying to find the probability of the numbers in a list.I have a list say:

a =[62.0, 0.0, 67.0, 69.0, 0.0, 76.0, 0.0, 0.0, 69.0, 70.0, 73.0, 0.0, 0.0, 56.0, 80.0, 0.0, 59.0, 65.0, 78.0, 0.0, 43.0, 0.0, 87.0]

i want to find out the probability of number from 0-25,25-50,50-100 and more than 100. i tried using this:

a.count(range(25))/len(a)
a.count(range(25,50))/len(a)

But am not getting the required results. Can someone help with whats wrong here?


Solution

  • a.count(range(25)) gives 0 because range(25) isn't an element of a. What you want to count is the occurrences of each individual element of range(25) within a, e.g.:

    >>> sum(a.count(i) for i in range(25))
    9
    

    Alternatively, you could iterate over each element of a and check it for inclusion in the range (I think this'll be a bit faster since in theory you don't need to iterate over a range to test whether something is in it):

    >>> sum(i in range(25) for i in a)
    9