Prince Dinar Prince Dinar - 1 month ago 7
Python Question

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))))

Answer
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] / float(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)]