我需要将字母成绩添加到一个现有的列表中,这个列表中有学生ID和学生积分,范围是0-100.我认为我需要将字母成绩追加到列表中,但我甚至还不知道如何将数字转换为字母成绩。
student_grades = []
for i in range(0,20):
student_grades.append(s[i])
for student in student_grades:
Data = student.split("\t")
letter_grade = Data[1]
if (80 <= Data <= 100):
letter_grade = 'A'
elif (65 <= Data <= 79):
letter_grade = 'B'
elif (50 <= Data <= 64):
letter_grade = 'C'
elif (35 <= Data <= 49):
letter_grade = 'D'
else:
letter_grade = 'F'
print(letter_grade)
但每次我尝试运行它,用不同的if语句变化,程序的反应是--------。TypeError: '<=' not supported between instances of 'int' and 'str'
编辑:有没有更有效的方法?我的工作簿告诉我,我需要 "定义一个函数,它根据学生的标记计算学生的字母等级。也就是在参数中传递的分数,它返回相应的字母(作为一个字符串)。换算依据如下表格:A 80 - 100B 65 - 79C 50 - 64D 35 - 49E 0 - 34。
@Grismar和@revliscano指出了关于数据类型int和str的重要注意事项。这里有一个工作代码的例子。
student_grades = []
# This is a list of grade numbers. for example, `[20,17,61]`. I assume that you
# store student names and ID and other information on another list.
# The following line of code will throw an exception if `student_grades` has
# incorrect format
for x in student_grades:
assert isinstance(x,(int,float))
# while `isinstance` is `python`'s built-in function to judge if `x` is of
# type `int` or `float`, both are acceptable for grades.
def letter_grade(num):
letter = None
if num < 35:
letter = 'F'
elif num < 50:
letter = 'D'
elif num < 65:
letter = 'C'
elif num < 80:
letter = 'B'
else:
letter = 'A'
return letter
# Note how rewriting the cases make the conditions concise.
converted_grades = [letter_grade(num) for num in student_grades]
print(converted_grades)
现在我把它包在一个函数里,使它更容易使用.
def num_to_letter(nums):
def letter_grade(num):
letter = None
if isinstance(num,(int,float)):
if num < 35:
letter = 'F'
elif num < 50:
letter = 'D'
elif num < 65:
letter = 'C'
elif num < 80:
letter = 'B'
else:
letter = 'A'
return letter
return [letter_grade(num) for num in nums]
一些测试。
print(num_to_letter([1,50,80]))
>> ['F', 'C', 'A']
print(num_to_letter([1,50,'invalid_score']))
>> ['F', 'C', None]
如果数据类型不正确,函数就会把字母等级保留为: None
而不抛出异常。