繁体   English   中英

计算Python 3中列表的平均值

[英]Calculating the average of a list in Python 3

我目前正在尝试计算由类中的方法创建的列表的平均值。 首先,所有信息都传递给一个类,该类记录/返回从主函数传递来的数据。 问题是我要从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

您当前的代码是错误的,因为您在每次迭代中都将count除以countcount之前实际上是标记数)。 使用一系列值来计算平均值非常容易:

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

您无需传递任何内容; 所有实例属性都可以通过self 除非明确要求您从平均值中排除零分,否则应将其计算在内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM