python - 如何在 Python 的成绩单中找到百分比?
问题描述
请指导我;我想打印三个主题的百分比。我制作的程序是:
subjects = ["Maths","English","Science"]
names = ["Talha","Fazeel","Usayd","Mujtuba","Sufyan","Aukasha","Moiz","Mohid","Wasil"]
scores = [[10,8,7],[8,8,6],[7,5,4],[4,0,2],[3,9,4],[7,8,3],[8,7,5],[9,5,7],[8,7,9]]
a=0
while a<len(names):
highest=scores[a][0]
subject=subjects[0]
i=0
while i<=2:
if scores[a][i]>highest:
highest=scores[a][i]
subject=subjects[i]
i=i+1
print(names[a]+"'s Highest in",subject+":", highest)
a=a+1
我不明白如何在这个程序中找到百分比。请告诉我要添加什么以及在哪里添加?我的预期输出是:
Talha's Highest in Maths: 10 and percentage is: 83.4%
Fazeel's Highest in Maths: 8 and percentage is: 73.34%
Usayd's Highest in Maths: 7 and percentage is: 53.34%
Mujtuba's Highest in Maths: 4 and percentage is: 20%
Sufyan's Highest in English: 9 and percentage is: 53.34%
Aukasha's Highest in English: 8 and percentage is: 60%
Moiz's Highest in Maths: 8 and percentage is: 66.67%
Mohid's Highest in Maths: 9 and percentage is: 70%
Wasil's Highest in Science: 9 and percentage is: 80%
解决方案
有很多方法可以通过使用 prebuild 函数或 python 提供的方法来改进代码。
subjects = ["Maths", "English", "Science"]
names = ["Talha", "Fazeel", "Usayd", "Mujtuba", "Sufyan", "Aukasha", "Moiz", "Mohid", "Wasil"]
scores = [[10, 8, 7], [8, 8, 6], [7, 5, 4], [4, 0, 2], [3, 9, 4], [7, 8, 3], [8, 7, 5], [9, 5, 7], [8, 7, 9]]
a = 0
while a < len(names):
h_marks = (max(scores[a]))
subject = subjects[scores[a].index(h_marks)]
percentage = round(sum(scores[a])/30*100, 2)
print(f"{names[a]}'s Highest in {subject}: {h_marks} and percentage is: {percentage}%")
a = a+1
在这段代码中
- max(list) 将返回列表中的最大值。
- list.index(x) 将返回列表“list”中“x”的索引。
- round(x,y) 将用“y”个十进制数字四舍五入您的浮点数“x”。
- f"Value of x: {x}" 称为字符串格式化,它在创建和初始化字符串时将 x 的值放入字符串中。
推荐阅读
- c++ - std::fstream 需要很长时间才能将大数据写入 .csv 文件
- visual-studio - Xamarin 应用程序无法在 Android 设备上调试
- python - 如何打印循环迭代的最后一个值
- python - 使用 SavedModel 或 freeze_graph.pb 进行 Tensorflow 2.0 推理
- vue.js - vuejs 属性中的这个语法 `${k}` 是什么?
- puppeteer - 自 2019 年 8 月 15 日起,Puppeteer 下载未能安装 Chromium
- c# - 在 unity3D 中编辑或不编辑 Transform.rotation
- javascript - 使用 javascript 自动引用
- linux - 删除具有相似名称的文件,除了一个?
- oracle - 替换字符串中点后的空格