Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i find the percentage of the most common element in a list?

I have been recently using Counter().most_common but the problem is that I need to turn the bit where it shows how much it came up into a percentage, for example:

[(2, 5), (10, 5)]

to:

[(2, 50%), (10, 50%)]

Is there any way of doing this using Counter().most_common, or any other method?

Here is part of my code:

    while count < int(DR):
        count = count + int(1)
        DV.append(random.randint(1, int(DI)))
    if count == int(DR):
        print ('\n(The Number that was rolled , the amount of times it came up):')
        global x
        print (Counter(DV).most_common(int((DI))))
like image 290
Prince Dinar Avatar asked Jun 17 '14 21:06

Prince Dinar


1 Answers

from collections import Counter
l = [1, 1, 2, 2, 2, 2, 2, 3, 4, 10, 10, 10, 10, 10]
c = Counter(l)
[(i, c[i] / len(l) * 100.0) for i in c]

Output, in the form (element, % of total)

[(1, 14.285714285714285),
 (2, 35.714285714285715),
 (3, 7.142857142857142), 
 (4, 7.142857142857142), 
 (10, 35.714285714285715)]

To list them in order you can use collections.Counter.most_common

>>> [(i, c[i] / len(l) * 100.0) for i, count in c.most_common()]
[(2, 35.714285714285715),
 (10, 35.714285714285715),
 (1, 14.285714285714285),
 (3, 7.142857142857142),
 (4, 7.142857142857142)]
like image 90
Cory Kramer Avatar answered Oct 17 '22 20:10

Cory Kramer