python 找出学生中谁得了最高分

3bygqnnd  于 2023-01-24  发布在  Python
关注(0)|答案(4)|浏览(165)

我是python的新手,目前正在做一个项目,对学生的分数进行排序和计算,我被要求找出学生中谁的分数最高。
如果只有一名学生,则将输出:[姓名]获得最高分。如果只有两名学生,它将输出:[姓名]和[姓名]获得最高分。如果两个以上的学生,它将输出:[姓名],[姓名]和[姓名]获得最高分。
然而,我被困在两个以上的学生,不知道如何满足上述要求,例如,如果有一个班的400名学生,他们都得到了相同的分数,我的程序不工作,我想到了递归,但我不知道这是一个很好的方向或没有。
这是我现在得到的:

marks = {'Sally': 65, 'Ken': 61, 'Michael': 88, 'Yan': 67, 'Mary': 88,'May': 88}
highest = max(marks.values())
n = [k for k, v in marks.items() if v == highest]

if len(n)==1:
    print(n[0],' got the highest mark')
elif len(n)==2:
    print(n[0],'and',n[1],' got the highest mark')
elif len(n)==3:
    print(n[0],',',n[1],'and',n[2],' got the highest mark')

谢谢!

bpsygsoo

bpsygsoo1#

你可以使用''.join(<listhere>)来完成它。

marks = {'Sally': 65, 'Ken': 61, 'Michael': 88, 'Yan': 67, 'Mary': 88,'May': 88}
highest = max(marks.values())
n = [k for k, v in marks.items() if v == highest]
str1 = ', '.join(n)
print(str1, 'got the highest mark')
zf9nrax1

zf9nrax12#

可以使用简单的for循环修改if块,如下所示

for i in range(len(n)):
if(i < len(n)-1): # for the name which is not the last of n
    print(n[i]+", ", end="")
else:
    print("and " + n[i] + " got the highest mark")
yrefmtwq

yrefmtwq3#

mystr = ', '.join(n[:-1]) + ' and ' + n[-1] if len(n)>1 else n[0] 
print ( mystr + ' got the highest marks')
#Michael, Mary and May got the highest marks
x0fgdtte

x0fgdtte4#

使用for循环并列出索引。

marks = {'Sally': 65, 'Ken': 61, 'Michael': 88, 'Yan': 67, 'Mary': 88, 'May': 88}
highest = max(marks.values())
toppers_list = [name for name, score in marks.items() if score == highest]

for student in toppers_list[:-1]:
    print(student, end=', ')

print("and", toppers_list[-1], "scored highest marks.")

toppers_list[:-1]创建一个列表,其中包含除最后一名学生外得分最高的所有学生的姓名。
print(student, end=', ')将防止在每次打印后换行,并将用逗号(和空格)分隔所有名称。

    • 输出:**
Michael, Mary, and May scored highest marks.

希望这个有用。

相关问题