Search code examples
pythonpython-3.xcounterpercentage

How to extract percentages from counter function


I got this function and from the counter, I wanted to extract the numbers of each element in the list and to convert it into percentages so I can know the percentage of each element in the list.

from collections import Counter
import random

dice_rolls = []
for i in range(0, dice_amount):
    dice_rolls.append(random.randint(1,dice_face))
num = Counter(dice_rolls)

Solution

  • Sure - get the total count with sum over the counter's values (though you could just use len(dice_rolls) or dice_amount for that, of course), and then print things out.

    The Counter is a dict at heart, so you could just use .items(), but you can also use .most_common(), which yields pairs in decreasing count order.

    import collections
    import random
    
    dice_rolls = []
    dice_amount = 42
    dice_face = 6
    for i in range(dice_amount):
        dice_rolls.append(random.randint(1, dice_face))
    num = collections.Counter(dice_rolls)
    
    total = sum(num.values())
    for face, count in num.most_common():
        print(f"{face}: {count} ({count/total:.2%})")
    

    prints out eg

    6: 8 (19.05%)
    3: 8 (19.05%)
    2: 7 (16.67%)
    1: 7 (16.67%)
    4: 6 (14.29%)
    5: 6 (14.29%)