首页 > 解决方案 > 每次出现都要重复的 if 语句

问题描述

我有一个列表,其中包含不同的课程名称,后跟逗号,然后是等级。

courses = ['COMP 1000,A+', "MATH 1000,A+", 'SCIE1000,B+"]

对于列表中出现的每次成绩,我将其更改为成绩点值并将其添加到不同的列表中。然后从那里我通过找到平均值来计算 GPA。我为此使用以下代码:

if any("A+" in n for n in courses):
    grades.append(4.30)
if any("B+" in n for n in courses):
    grades.append(3.30)

这适用于每个等级重复一次的列表,但对于上面的课程列表,有两个 A+,但 4.30 只添加一次。每次成绩在列表中时,有没有办法将 4.30 添加到新列表中?

谢谢

标签: pythonpython-3.xlistif-statement

解决方案


You're going about this the wrong way. Loop over the courses, split on the comma, and look up the grade-to-grade-point conversion in a dict (the equivalent of a case statement in other languages).

courses = ['COMP 1000,A+', 'MATH 1000,A+', 'SCIE1000,B+']
grades = []

grade_to_grade_point = {
    "A+": 4.30,
    "B+": 3.30,
    # ...
    }
for course in courses:
    course_name, grade = course.split(',')
    grades.append(grade_to_grade_point[grade])

print(grades)  # -> [4.3, 4.3, 3.3]

Or as a list comprehension:

grades = [grade_to_grade_point[c.split(',')[1]] for c in courses]

推荐阅读