基本思路就是定义两个函数,分别计算班级平均和学生平均分,因为成绩表格式并不是太合理,所以应该考虑先整理成绩表,整理成字典格式处理起来会直观很多,尤其是数据量比较大的时候,当然基于当前数据,也可以直接计算,我给一种直接计算的方案:
def calculate_class_ave(stu_list, courceName):
total = 0
for stu_info in stu_list:
stu_info_arr = [s.replace(' ','') for s in stu_info.split(",")]
for info in stu_info_arr:
if courceName.replace(' ','') in info:
total += int(info.split(":")[1])
print(f"课程{courceName}的班级平均成绩是:{total/len(stu_list)}")
return total/len(stu_list)
def calculate_student_ave(stu_list, stu_no):
total = 0
for stu_info in stu_list:
if stu_no in stu_info:
stu_info_arr = [s.replace(' ','') for s in stu_info.split(",")]
total = int(stu_info_arr[3].split(":")[1])+int(stu_info_arr[4].split(":")[1])+int(stu_info_arr[5].split(":")[1])
break
print(f"学生{stu_no}的平均成绩是{total/3}")
return total/3
Student_list = ['John, Jam, 2345, ITEC 1401: 65, BIT 2008: 72, BIT 1000: 79', 'Emma, Hu, 4321, ITEC 1401: 88, BIT 2008: 80, BIT 1000: 82', 'Kamil, Pavlowski, 4114, ITEC 1401: 92, BIT 2008: 90, BIT 1000: 95', 'Mike, Orr, 5432, ITEC 1401: 92, BIT 2008: 89, BIT 1000: 96' ]
class_ave = calculate_class_ave(Student_list, 'ITEC 1401')
student_ave = calculate_student_ave(Student_list, '5432')
如有帮助,请采纳!