简体   繁体   English

计算Python 3中列表的平均值

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

I am currently trying to calculate the average of a list created by a method in a class. 我目前正在尝试计算由类中的方法创建的列表的平均值。 Firstly all information is passed to a Class that records/returns the data passed through from the main function. 首先,所有信息都传递给一个类,该类记录/返回从主函数传递来的数据。 The issue is what do I pass in from the main function to firstly retrieve the self._marks list and then manipulate it in order for the average to be returned. 问题是我要从main函数传入什么内容,以便首先检索self._marks列表,然后对其进行操作以返回平均值。 Also am I using the correct code for the calculateAverageMark section? 我是否还在calculateAverageMark部分使用了正确的代码? Thanks in advance 提前致谢

Here is the code: 这是代码:

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

Your current code is incorrect because you divide by count in every iteration (and before count is actually the number of marks). 您当前的代码是错误的,因为您在每次迭代中都将count除以countcount之前实际上是标记数)。 Calculating the average is very easy with a list of values: 使用一系列值来计算平均值非常容易:

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

You don't need to pass anything in; 您无需传递任何内容; all instance attributes are available via self . 所有实例属性都可以通过self Unless you have specifically been told to exclude zero scores from the average, you should count them. 除非明确要求您从平均值中排除零分,否则应将其计算在内。

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

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