简体   繁体   中英

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

If you don't have the original data, you can still accomplish this just with the Counter .

OrderedDict([(i, str(round(count / sum(c.values()) * 100.0, 3)) + '%') for i, count in c.most_common()])

Where:

  • i is the item that was counted;
  • count is the count of that item;
  • c is the Counter object
  • 3 is the precision of the percentage

Performance can be improved if sum(c.values()) is moved outside of the list compression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM