擅长:python、mysql、java
<p>您需要检查<em>每个等级</em>,然后为该等级添加分数。您可以使用类似于<a href="https://stackoverflow.com/a/67643719/843953">j1-lee</a>的<code>if-else</code>梯形图来完成此操作,也可以使用将每个字母映射到其分数的词典:</p>
<pre><code>def gpa(grades):
grade_to_point = {"A": 4., "B": 3., "C": 2., "D": 1.}
total = 0.
for letter in grades:
total += grade_to_point.get(letter, 0.) # Get the value from the dict. 0 if letter wasn't found in the dict
return total / len(grades)
</code></pre>
<p>如果您愿意,可以使用<code>sum()</code>函数和生成器表达式对其进行pythonize</p>
<pre><code>def gpa(grades):
grade_to_point = {"A": 4., "B": 3., "C": 2., "D": 1.}
return sum(grade_to_point.get(letter, 0.) for letter in grades) / len(grades)
</code></pre>