python - 每次出现都要重复的 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 添加到新列表中?
谢谢
解决方案
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]
推荐阅读
- mysql - 如何在 mysql 中正确使用 soundex()
- python - 在seaborn中将箱线图转换为散点图
- asp.net-mvc - 如何从服务总线调用 API
- database - 如何使用delphi XE8获取数据库中元素的数量
- javascript - 列出在 AngularJS 中使用 $http.get 创建的列表中的所有元素
- ruby-on-rails - 在 Spree ruby gem 中缓存配置
- sql - 如何根据日期连接多个表中的值
- typescript - 如何使用 vue-class-component 构建 es6 vue-component 库
- java - hibernate.PersistentObjectException:分离的实体传递给持久化
- swift - swift3中的字符串变量比较