简体   繁体   中英

How to transform list elements into percentages

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

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

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

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