You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python类中计算n名学生的成绩总和与平均分?

解决任意数量学生成绩平均分计算问题

你当前的get_average方法只能手动累加固定索引的学生成绩,要支持任意数量的学生,只需要遍历课程里的所有学生,累加他们的成绩总和,再除以学生数量即可。

修改后的完整代码

class StudentInfo:
    def __init__(self, name, age, grade):
        self.studentname = name
        self.studentage = age
        self.studentgrade = grade
    
    # 可选优化:用@property让属性访问更符合Python风格
    @property
    def name(self):
        return self.studentname
    
    @property
    def age(self):
        return self.studentage
    
    @property
    def grade(self):
        return self.studentgrade


class Course:
    def __init__(self, name, maxstudents):
        self.nameofcourse = name
        self.maxstudents = maxstudents
        self.student = []

    def add_student(self, studentinfo):
        # 可选优化:限制学生数量不超过课程最大容量
        if len(self.student) < self.maxstudents:
            self.student.append(studentinfo)
            return True
        return False

    def get_average(self):
        # 处理空学生列表的情况,避免除以0报错
        if not self.student:
            return 0.0
        # 遍历所有学生累加成绩,自动适配任意数量的学生
        total_grade = sum(student.studentgrade for student in self.student)
        # 如果你想用自己定义的grade_1方法,也可以写成:sum(student.grade_1() for student in self.student)
        return total_grade / len(self.student)


# 测试示例
a = StudentInfo('karthi', 16, 100)
a2 = StudentInfo('lol', 16, 99)
a3 = StudentInfo('oo', 16, 90)
a4 = StudentInfo('test', 17, 95)  # 新增测试学生

b = Course('cs', 4)
b.add_student(a)
b.add_student(a2)
b.add_student(a3)
b.add_student(a4)
print(b.get_average())  # 输出 (100+99+90+95)/4 = 96.0
print(b.student[1].studentname)

关键修改说明

  1. 自动遍历求和:用生成器表达式sum(student.studentgrade for student in self.student)替代手动索引累加,不管课程里有多少学生,都会自动遍历并累加成绩。
  2. 边界情况处理:增加了空学生列表的判断,避免出现除以0的运行错误。
  3. 可选优化项:
    • 给StudentInfo的方法加上@property装饰器,让属性访问更简洁(比如student.name替代student.name())。
    • 在add_student中增加容量判断,防止添加超过课程最大人数的学生。

内容的提问来源于stack exchange,提问作者ganesh murthy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:45:34