我正在尝试编写一个计算和打印以下内容的Python程序:
程序首先要求用户输入案例数。对于每个案例,该程序应要求用户输入学生人数。对于每个学生,该程序要求用户输入学生的姓名和标记。对于每个案例,该计划报告平均分数,最高分和获得最高分的学生的姓名。
另外 如果CASE中有多个得分最高的人,则该程序应仅报告第一次出现。 平均分和最高分应该有2位小数。 输出应该与示例程序输出中的一样。
到目前为止,我一直在尝试的是:
grade=[]
name_list=[]
cases=int(input('Enter number of cases: '))
for case in range(1,cases+1):
print('case',case)
number=int(input('Enter number of students: '))
for number in range (1,number+1):
name=str(input('Enter name of student: '))
name_list.append(name)
mark=float(input('Enter mark of student:'))
grade.append(mark)
highest= max (grade)
average=(sum(grade)/number)
high_name=grade.index(max(grade))
print('average',average)
print('Highest',highest)
print (high_name)
这就是我到目前为止所破译的内容。我现在最大的问题是获得高分的个人名字。任何想法和反馈都非常感谢。至于下面发布的答案,恐怕我唯一不理解的是字典功能,但其他部分确实对我有意义。
答案 0 :(得分:1)
这类似于作业,在细节上太特定。
无论如何,official docs是开始学习Python的好地方。 它们非常清晰,并且有大量有用的信息,例如
range(start, end)
:如果省略 start 参数,则默认为0
关于lists
的部分应该为您提供一个良好的开端。
答案 1 :(得分:1)
numcases = int(input("How many cases are there? "))
cases = list()
for _ in range(numcases):
# the _ is used to signify we don't care about the number we're on
# and range(3) == [0,1,2] so we'll get the same number of items we put in
case = dict() # instantiate a dict
for _ in range(int(input("How many students in this case? "))):
# same as we did before, but skipping one step
name = input("Student name: ")
score = input("Student score: ")
case[name] = score # tie the score to the name
# at this point in execution, all data for this case should be
# saved as keys in the dictionary `case`, so...
cases.append(case) # we tack that into our list of cases!
# once we get here, we've done that for EVERY case, so now `cases` is
# a list of every case we have.
for case in cases:
max_score = 0
max_score_student = None # we WILL need this later
total_score = 0 # we don't actually need this, but it's easier to explain
num_entries = 0 # we don't actually need this, but it's easier to explain
for student in case:
score = case[student]
if score > max_score:
max_score = score
max_score_student = student
total_score += score
num_entries += 1
# again, we don't need these, but it helps to demonstrate!!
# when we leave this for loop, we'll know the max score and its student
# we'll also have the total saved in `total_score` and the length in `num_entries`
# so now we need to do.....
average = total_score/max_entries
# then to print we use string formatting
print("The highest score was {max_score} recorded by {max_score_student}".format(
max_score=max_score, max_score_student=max_score_student))
print("The average score is: {average}".format(average=average))