我正在编写一个代码作为我所教类(class)的成绩簿。虽然我有一个没有类的工作代码,但我正在学习并尝试将类合并到我的代码中。
我有一个类StudentSpecs
。类中定义了很多东西(例如姓名和ID号),但相关部分是:
class AstronomyLab154L:
class StudentSpecs:
def __init__(self, points=None, grade=None):
self.points = points
self.grade = grade
def __str__(self):
return "\nTotal Points: %s \nGrade: %s" %(self.points, self.grade)
def set_points(self, points):
self.points = points
def set_grade(self, grade):
self.grade = grade
def get_points(self, points):
return self.points
def get_grade(self, grade):
return self.grade
使用此代码,我的代码(可根据请求提供,但为了缩短帖子而省略)将读取 .csv 文件(通过 MS Excel)并为中的每一行创建 StudentSpecs
类的实例文件(每行代表不同的学生,每列代表不同的作业分数)。因此,我可以像这样循环访问每个学生的总分和字母等级。
## classroom = list of student instances
for student in classroom:
print(student.points, student.grade)
## example of output
88.0 B
94.0 A
82.5 B-
52.0 F
我的目标是创建教室
数据的直方图,以便 x 轴刻度标签(以 bin 为中心)将存储字母成绩,y 轴将存储学生人数与相应的字母等级。我可以使用 numpy 和 matplotlib 制作直方图。但是,我不知道如何将 Counter
应用于我的类实例。我的尝试如下。
from collections import Counter
def display_classroom_specs(classroom):
## initialize dict since Counter is a dict
grade_counts = {}
## update dictionary for each student in classroom
for student in classroom:
grade_counts += Counter(student.grade) ## y-axis of histogram
return grade_counts
print(display_classroom_specs(classroom))
## throws an error
TypeError: unsupported operand type(s) for +=: 'dict' and 'Counter'
我认为我应该使用 dictionary.update
方法,尽管我不确定如何在这种情况下应用它。
如何将计数器应用到我的类实例?
最佳答案
您可以只传递一个生成器表达式,然后让 Counter
完成其余的工作。
c = Counter(student.grade for student in classroom)
关于python - 如何将 Counter 应用于循环调用的多个类实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46761851/