我正在尝试在我构建的类中获得一个工作方法。本课程累积了给定学生的课程历史。每门课程都是一份列表(姓名,成绩,学分等),该列表是该学生所有课程总列表的一部分。这是一个示例课程历史:
class StudentInfo(object):
def __init__(self, last, first, dob):
self.last=last
self.first=first
self.dob=dob
self.gradehist=[]
def __add__(self, course):
return self.gradehist.append(course)
def cumulativegpa(self):
cred = [item[2] for item in self.gradehist]
grad = [item[1] for item in self.gradehist]
gc = [grad[i]*cred[i] for i in range(len(grad))]
hrs = sum(cred)
gpasum = sum(gc)
cumgpa = gpasum/hrs
return cumgpa
def semgpa(self, x, y):
semcred=[]
semgrad=[]
for i in self.gradehist:
if self.gradehist[3] == x and self.gradehist[4] == y:
semcred.append([item[2] for item in self.gradehist])
for i in self.gradehist:
if self.gradehist[3] == x and self.gradehist[4] == y:
semgrad.append([item[1] for item in self.gradehist])
return semcred, semgrad`
s1=StudentInfo('Bob','Dole', '1-1-1911')
s1 + ['English 1', 4, 3, 'Fall', '2009']
s1 + ['English 2', 3.7, 3, 'Spring', '2010']
etc
我可以计算累积的GPA,但我发现很难确定一个学期的GPA。这是我的相关代码:
def semgpa(self, x, y):
当我输入s1.cumulativegpa()时,它会返回正确的总gpa,但是s1.semgpa(' Fall',' 2009')会返回" [],[ ]" 我哪里错了?
修改:更新for course in self.gradehist:
if course[3] == x and course[4] == y:
semcred.append([item[2] for item in course])
以包含
{{1}}
答案 0 :(得分:0)
我不确定这是不是你想要的,但你可以这样试试:
def semgpa(self, x, y):
semcred=[]
semgrad=[]
for row in self.gradehist:
if row[3] == x and row[4] == y:
semcred.append(row[2])
semgrad.append(row[1])
return semcred, semgrad
首先,迭代所有行。然后,您只获取属于所选学期的行。然后,您可以将这些行中的值附加到新列表中。