Home > OS >  How to transform list elements into percentages
How to transform list elements into percentages

Time:09-28

I have this code:

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

and i wanted it to display for example: there was 5 number 1, 6 number 2, etc... And, if possible, say what percentage of the list is what element. For example: 1% was 5, 6% was seven, etc

CodePudding user response:

Use count method to get the number of elements for each dice roll.

Example with your code (dice rolls from 1 to 6) :

import random

if __name__ == "__main__":

    count = 10
    dice_rolls = list()

    random.seed()

    for i in range(count):
        dice_rolls.append(random.randint(1, 6))

    print(f"Dice rolls: {dice_rolls}")
    for i in range(6):
        print(f"Dice = {i   1} - Count = {dice_rolls.count(i   1)}")

CodePudding user response:

  1. find the unique elemnts in that list and store it in a seperate list

    # traverse for all elements
     for x in list1:
         # check if exists in unique_list or not
         if x not in unique_list:
             unique_list.append(x)
    

unique list contains all the unique elements.

  1. Now use the unique list and count the occourances of unique elements : (idk why but this part is not indenting as code)

    import operator as op for x in unique_list: print(f"{x} has occurred {op.countOf(list1, x)} times") val_list.append(x,op.countOf(list1,x))

3 Now you have the unique elements and tthe occourance now find the percentage by

value_1_percent = (value_1_count/len(original _list))*100

CodePudding user response:

As simple as possible:

#! /usr/bin/env python3

import sys,random


if __name__ == "__main__":
    #all helpful variables
    help_dictionary ={}
    dictionary_with_percents ={}
    dice_amount = 100
    diceface = 6
    dice_rolls = []

    #your code
    for i in range(0, dice_amount):
        dice_rolls.append(random.randint(1,diceface))

    #lets check how many times each face occured
    for i in dice_rolls:
        help_dictionary[i]= dice_rolls.count(i)
    
    #lets check what is the percentage for each face
    for face , amount in help_dictionary.items():
        dictionary_with_percents[face] = str((amount/dice_amount)*100) '%'

    #lets print the result
    print (dictionary_with_percents)

You can also use dict comprehension instead of for loops, here ist only my idea ;-)

  • Related