如何在python中使用类显示平均出勤率

时间:2017-09-21 11:51:32

标签: python class variables average

我有以下代码试图显示所有'创建的平均出勤率。学生们。我有一个studentCount,可以计算和打印所有存在的学生,但似乎无法达到出现这种情况的逻辑。我的尝试如下:

代码

class Student: 
    studentCount=0
    attendanceAverage=0

    def __init__(self, name, form,special_interest,attendance, merits):  #additional variables added here such as special_interest, merits, attendance
        self.name=name
        self.form=form
        self.special_interest=special_interest #additions for the above made here
        self.attendance=attendance
        self.merits=merits

        Student.studentCount+=1
        Student.attendanceAverage=attendance/Student.studentCount

    def displayCount(self):
        print("Total Students:",Student.studentCount)

    def displayStudent(self): 
        print("=Name:",self.name,"=Form:",self.form,"Special Interest:",self.special_interest,"Attendance:",self.attendance,"Merits:",self.merits) #updating the print method for displayStudent to include additional variables

    def displayAttendance(self):
        print("=Name:",self.name,"=Attendance:",self.attendance)



student1=Student("Student1","9F","Guitar",10,200) 
student2=Student("Student2","9R","Chess",7,488) 
student3=Student("Student3","9T","Dance",9,770)
student1.displayStudent() 
student2.displayStudent()
student3.displayStudent()
student3.displayAttendance()

print("Average Attendance:",Student.attendanceAverage)
print("Total Students:",Student.studentCount)  #prints a total count of students

当前输出

=Name: Student1 =Form: 9F Special Interest: Guitar Attendance: 10 Merits: 200
=Name: Student2 =Form: 9R Special Interest: Chess Attendance: 7 Merits: 488
=Name: Student3 =Form: 9T Special Interest: Dance Attendance: 9 Merits: 770
=Name: Student3 =Attendance: 9
Average Attendance: 3.0
Total Students: 3

什么不行..

在这种情况下,平均出勤率显然应该是10,7和9的平均值。我尝试了下面的各种事情(试图首先申报出席人数......之后我可以计算平均数)......

    Student.attendanceCount=? #sum all the existing values for attendance
    Average=attendanceCount/Student.studentCount

这是尝试首先总结各个学生的出勤率,然后我会继续平均他们。我无法通过语法来完成第一件事(获取每个学生的所有值)。有没有pythonic或最好的方法吗?

对于已接受的答案,有人可以提供问题的建议解决方案,并提供适当的评论和解释,以及(如果适用)更优雅的方法来解决同一问题。

4 个答案:

答案 0 :(得分:1)

它不起作用,因为您没有跟踪TOTAL出勤率。每次创建Student类对象时,您使用的是新的出勤值,而不是累计的出勤值。问题在于:

Student.attendanceAverage=attendance/Student.studentCount

未经测试,但应该有效:添加一个跟踪总出勤率的新班级变量:

class Student: 
    studentCount=0
    attendanceAverage=0
    totalAttendance = 0

def __init__(self, name, form,special_interest,attendance, merits):  
    self.name=name
    self.form=form
    self.special_interest=special_interest 
    self.attendance=attendance
    self.merits=merits
    Student.totalAttendance += attendance

    Student.studentCount+=1
    Student.attendanceAverage=Student.totalAttendance/Student.studentCount

答案 1 :(得分:1)

问题是每次实例化Student.attendance类时都要分配静态变量Student。因此,根据您的代码,平均关注度为9 / 3 = 3

你可以像这样引入一个和变量:

`class Student:
studentCount=0
attendanceAverage=0
attendanceSum = 0

def __init__(self, name, form,special_interest,attendance, merits):  #additional variables added here such as special_interest, merits, attendance
    self.name=name
    self.form=form
    self.special_interest=special_interest #additions for the above made here
    self.attendance=attendance
    self.merits=merits

    Student.studentCount+=1
    Student.attendanceSum += attendance # increment Student's static sum of attendances by this student's attendance
    Student.attendanceAverage = Student.attendanceSum / Student.studentCount`

答案 2 :(得分:1)

其他答案已经指出了为什么你的代码不能正常工作,但是有一个特定的原因你需要一个类吗?如果您使用像Pandas这样的库进行数据操作可能会更有用。

import pandas as pd

students = pd.DataFrame([['Student1','9F','Guitar',10,200],
                         ['Student2','9R','Chess ',7,488],
                         ['Student3','9T','Dance ',9,770]], 
                        columns=["name", 
                                 "form", 
                                 "special_interest", 
                                 "attendance", 
                                 "merits"])

print("All students")
print(students)
print("")
print("Student3 Attendance: ", students[students['name'] == "Student3"]['attendance'].values[0])
print("Average attendance", students['attendance'].mean())
print("Total Students", len(students))

输出:

All students
       name form special_interest  attendance  merits
0  Student1   9F           Guitar          10     200
1  Student2   9R           Chess            7     488
2  Student3   9T           Dance            9     770

Student3 Attendance:  9
Average attendance 8.666666666666666
Total Students 3

答案 3 :(得分:1)

+1用于上课!我知道一开始很难理解。

您的问题是您在一个类中分配变量,假设它们将被全局更改(即代码中的任何位置)。如果您将studentCount放在班级Student中,则每次处理时都会更改StudentCount。最后一个学生有9个出勤率,因此class Student: def __init__(self, name, form,special_interest,attendance, merits): self.name=name self.form=form self.special_interest=special_interest self.attendance=attendance self.merits=merits students = [] # create an empty list that will contain all your students as objects of your class student1=Student("Student1","9F","Guitar",10,200) students.append(student1) # add your instances/objects to the list student2=Student("Student2","9R","Chess",7,488) students.append(student2) student3=Student("Student3","9T","Dance",9,770) students.append(student3) avg = float(sum(student.attendance for student in students))/len(students) # sum up the attendance of all students and divide it by their number 设置为9(您将初始值0加9)。

我的解决方案是在列表中跟踪您的对象/学生并解决他们在课堂外的个人出勤问题,或将他们放在一个单独的课程中。

sum(student.attendance for student in students)

编辑:我将NSUUID *uuid = [[NSUUID UUID] initWithUUIDString:uuidString]; 转换为float,因为我使用的是python 2.7。如果我保留整数值,它将执行整数除法。如果你在python 3.x中编码,你可以省去dtype-conversion。