-2
grade=[]
names=[]
highest=0


#taking number of calues

cases=int(input('Enter number of cases: '))
for case in range(1,cases+1):
    print('case',case)

    #taking number of students

    number=int(input('Enter number of students: '))
    for numbers in range (1,number+1):

        #getting name and marks
        name=str(input('Enter name of student: '))
        names.append(name)
        mark=float(input('Enter mark of student:'))
        grade.append(mark)


    print('Case',case,'result') 

    #printing the results!
    average=float(sum(grade)/number)
    print('Average is: %.2f '%(average))
    print('Highest Score is: %.2f'%(max(grade)))
    print('Student with highest score: ',names[grade.index(max(grade))])

output->Enter number of cases: 2
case 1
Enter number of students: 2
Enter name of student: josh
Enter mark of student:98
Enter name of student: sarah
Enter mark of student:87
Case 1 result
Average is: 92.50 
Highest Score is: 98.00
Student with highest score:  josh
case 2
Enter number of students: 3
Enter name of student: shania
Enter mark of student:78
Enter name of student: arleen
Enter mark of student:89
Enter name of student: zoya
Enter mark of student:89
Case 2 result
Average is: 147.00 
Highest Score is: 98.00
Student with highest score:  josh

我的平均 在 3 种情况下被搞砸了,它也没有显示出最高的!我想知道如果有 2 次相同的事件,我怎样才能获得最高值。最高将仅是第一次出现。你们明白我的意思吗?

4

2 回答 2

2

问题在于,在case循环的第二次迭代中,您还要查看前一个循环中的名称和等级,因为您从未清空列表。您需要在循环开始时清空列表。在循环顶部创建空列表:

for case in range(1,cases+1):
    print('case',case)
    grade=[]
    names=[]
    highest=0

您可以(并且应该)这样做,而不是在文件顶部定义变量。


要查看出了什么问题(在添加我的修复之前),请执行以下操作:

average=float(sum(grade)/number)
print(grade)
print(names)
print('Average is: %.2f '%(average))
print('Highest Score is: %.2f'%(max(grade)))
print('Student with highest score: ',names[grade.index(max(grade))])

您将看到列表具有上一次循环迭代的值。

于 2014-02-11T06:20:58.390 回答
0

基本上,问题在于列表在循环本身的开头被填充,尝试在循环迭代之前清除列表。为此:

for case in range(1,cases+1):
     print(`case`,case)
     grade=[]
     names=[]
     highest=0

通过case循环的第二次迭代在这里产生了问题

于 2014-02-11T06:25:40.853 回答