![](/img/trans.png)
[英]How to filter elements from a list based in another list and get percentages
[英]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)}")
找到該列表中的唯一元素並將其存儲在單獨的列表中
# 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)
唯一列表包含所有唯一元素。
現在使用唯一列表並計算唯一元素的出現次數:(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.