[英]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.并且我希望它显示例如:有 5 个数字 1、6 个数字 2 等......并且,如果可能的话,说出列表的百分比是什么元素。 For example: 1% was 5, 6% was seven, etc例如:1% 是 5,6% 是 7,等等
Use count
method to get the number of elements for each dice roll.使用count
方法获取每个掷骰子的元素数。
Example with your code (dice rolls from 1 to 6):您的代码示例(骰子从 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)}")
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.唯一列表包含所有唯一元素。
Now use the unique list and count the occourances of unique elements: (idk why but this part is not indenting as code)现在使用唯一列表并计算唯一元素的出现次数:(idk 为什么,但这部分没有缩进为代码)
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))导入运算符作为 x 在 unique_list 中的操作: print(f"{x} 已发生 {op.countOf(list1, x)} 次") val_list.append(x,op.countOf(list1,x))
3 Now you have the unique elements and tthe occourance now find the percentage by 3 现在你有了独特的元素,现在找到百分比
value_1_percent = (value_1_count/len(original _list))*100 value_1_percent = (value_1_count/len(原始_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;-)您也可以使用 dict 理解而不是 for 循环,这只是我的想法;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.