我是stackoverflow的新手,并且有点困在我的Python任务上。
这就是问题:
编写一个程序
MaximumScore.py
,该程序会收到学生证,姓名和分数 由学生获得。输出应显示最高分和获得该分数的学生 最高分。
所需的输出如下所示:
Enter student id and score: 101, 89.5
Enter student name: Albert
Enter student id and score: 102, 92.5
Enter student name: Bill
Enter student id and score: 103, 95.5
Enter student name: Capa
Enter student id and score: 104, 79.5
Enter student name: Danny
Enter student id and score: 105, 90.5
Enter student name: Edgar
Maximum score: 95.5
Student id: 103
Student name: Capa
我的问题是如何获得获得最高分的家伙的身份证和姓名?我也不知道如何获得名单。我觉得我在这里缺少一些重要的东西。
到目前为止,这是我的代码:
def main():
idnum = list()
score= list()
name=list()
n =5
for i in range(int(n)): idnum,score = input("Enter student id and score : ").split(",")
print "Maximum Score ", max(score)
main()
答案 0 :(得分:1)
您应该考虑使用dict而不是list。然后在dict {' id':'得分'}您可以按ID排序和打印分数。使用你赢得的三个列表;能够将一个列表的元素与其他列表的元素连接起来。
在这种情况下阅读有关字典的python手册。它们是非常好的书面手册。
关于dict你可以使用ie dict={'id':['name','score']}
所以key是学生ID,这个键的值将是名字和分数的列表。它很容易导航。
答案 1 :(得分:0)
您可以使用Python的zip
函数
idnum = []
score = []
name = []
n = 3
for i in range(n):
id_score = input('Enter student id and score: ').split(',')
idnum.append(id_score[0])
score.append(id_score[1])
name_ = input('Enter student name: ')
name.append(name_)
save = zip(score,name,idnum)
for x in save:
if max(score) in x:
highest = x
break
print('Maximum score: ' + highest[0])
print('Student id: ' + highest[2])
print('Student name: ' + highest[1])
答案 2 :(得分:0)
您最好在一个列表中使用元组,并通过max
中的键找到lambda
值。
from collections import namedtuple
Student = namedtuple('Student', 'id name score')
def main():
students = []
n = 5
for i in range(n):
id, score = input('Enter student id and score: ').split(',')
id = int(id)
score = float(score)
name = input('Enter student name: ')
student = Student(id, name, score)
students.append(student)
student_max_score = max(students, key=lambda x: x.score)
print('Max score: {}'.format(student_max_score.score),
'Student id: {}'.format(student_max_score.id),
'Student name: {}'.format(student_max_score.name),
sep='\n')
main()
答案 3 :(得分:0)
Wright几乎拥有它 - zip是一个很好用的工具,但你应该只使用max
函数:
idnum = []
score = []
name = []
n = 3
for i in range(n):
id, score = input('Enter student id and score: ').split(',')
idnum.append(id)
# If you don't convert to float it will
# sort in ASCII order, which is not what you want
score.append(float(score))
name_ = input('Enter student name: ')
name.append(name_)
highest = max(zip(score,name,idnum))
print('Maximum score: ' + highest[0])
print('Student id: ' + highest[2])
print('Student name: ' + highest[1])