簡體   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