繁体   English   中英

如何将列表元素转换为百分比

[英]How to transform list elements into percentages

我有这个代码:

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

并且我希望它显示例如:有 5 个数字 1、6 个数字 2 等......并且,如果可能的话,说出列表的百分比是什么元素。 例如:1% 是 5,6% 是 7,等等

使用count方法获取每个掷骰子的元素数。

您的代码示例(骰子从 1 滚动到 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. 找到该列表中的唯一元素并将其存储在单独的列表中

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

唯一列表包含所有唯一元素。

  1. 现在使用唯一列表并计算唯一元素的出现次数:(idk 为什么,但这部分没有缩进为代码)

    导入运算符作为 x 在 unique_list 中的操作: print(f"{x} 已发生 {op.countOf(list1, x)} 次") val_list.append(x,op.countOf(list1,x))

3 现在你有了独特的元素,现在找到百分比

value_1_percent = (value_1_count/len(原始_list))*100

尽可能简单:

#! /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)

您也可以使用 dict 理解而不是 for 循环,这只是我的想法;-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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