首页 > 解决方案 > 如何在 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%

标签: python

解决方案


有很多方法可以通过使用 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

在这段代码中

  1. max(list) 将返回列表中的最大值。
  2. list.index(x) 将返回列表“list”中“x”的索引。
  3. round(x,y) 将用“y”个十进制数字四舍五入您的浮点数“x”。
  4. f"Value of x: {x}" 称为字符串格式化,它在创建和初始化字符串时将 x 的值放入字符串中。

推荐阅读