我正在尝试在下图中的等级类别之间进行映射.然后我希望能够调用一个函数,将等级转换为等效格式的相同等级.例如:
def convert(num,letter,gpa): """Converts a grade into an equivalent grade. The desired output will be specified by -1 and the grade format not to be involved in the conversion will be specified by None. When converting to GPA,the minimum of the gpa range will be returned.""" >>> convert(83,None,-1) >>> 'A-' >>>convert(-1,'B+',None) >>>77
解决方法
我可能会做这样的事情,它避免了条件分支,并且很清楚你在转换时想要做什么.
class GradeRange: def __init__(self,pct,ltr,gpa): self.pct = pct self.ltr = ltr self.gpa = gpa class GradeTable: def __init__(self): self.ranges = [ GradeRange(range(0,50),'F',0.0),GradeRange(range(50,53),'D-',0.7),GradeRange(range(53,57),'D',1.0),GradeRange(range(57,60),'D+',1.3),GradeRange(range(60,63),'C-',1.7),GradeRange(range(63,67),'C',2.0),GradeRange(range(67,70),'C+',2.3),GradeRange(range(70,73),'B-',2.7),GradeRange(range(73,77),'B',3.0),GradeRange(range(77,80),3.3),GradeRange(range(80,85),'A-',3.7),GradeRange(range(85,90),'A',4.0),GradeRange(range(90,101),'A+',] def convert_pct(self,pct): for r in self.ranges: if pct in r.pct: return r.ltr,r.gpa def convert_ltr(self,ltr): for r in self.ranges: if r.ltr == ltr: return r.pct[0],r.gpa def convert_gpa(self,gpa): for r in self.ranges: if r.gpa == gpa: return r.pct[0],r.ltr