计算Python 3中列表的平均值

时间:2014-02-19 22:43:25

标签: python class methods

我目前正在尝试计算类中方法创建的列表的平均值。首先,所有信息都传递给一个类,该类记录/返回从main函数传递的数据。问题是我从main函数传入什么来首先检索self._marks列表然后操作它以便返回平均值。我也在使用calculateAverageMark部分的正确代码吗?提前致谢

以下是代码:

class Student :
    def __init__(self, id):
        self._studentId = id
        self._marks = []
    ##
    # Converts the student to a string .
    # @return The string representation .
    #

    # Sets the student's ID.
    # @param newId is the student's new ID.
    #
    def setStudentId(self, id):
        self._studentId = id

    ##
    # Gets the student's ID.
    # @return the student's ID
    #
    def getStudentId(self, newId):
        return self._newId

    ##
    # Appends a mark to the marks list
    #
    def addMark(self, mark):
        self._marks.append(mark)

    def __repr__(self) :
        # Build a string starting with the student ID
        # followed by the details of each mark .
        s = "Student ID :" + self._studentId + " "
        if len(self._marks) == 0 :
            s += " <none \n>"
        else :
            for mark in self._marks :
                s += " Course Module: " + mark.getModule() + " Raw Mark: " + str(mark.getRawMark())

        return s

    ##
    # Method to calculate the students average mark
    #
    def calculateAverageMark(self):
        totalMarks = 0
        count = 0
        for mark in self._marks :
            if mark == 0 :
                count = count
            else :
                count = count + 1

            totalMarks = totalMarks + mark
            average = totalMarks / count

        return average

1 个答案:

答案 0 :(得分:4)

您当前的代码不正确,因为您在每次迭代中除以count(并且count之前实际上是标记数)。使用值列表计算平均值非常简单:

def calculateAverageMark(self):
    if self._marks: # avoid error on empty list
        return sum(self._marks) / float(len(self._marks))

你不需要传递任何东西;所有实例属性均可通过self获得。除非你被特别告知要从平均值中排除零分,否则你应该统计它们。