如何简化评分系统函数中重复的 if-elif 语句? [英] How can I simplify repetitive if-elif statements in my grading system function?
问题描述
目标是构建一个程序,将分数从0 到 1"系统转换为F 到 A"系统:
The goal is to build a program to convert scores from a '0 to 1' system to an 'F to A' system:
- 如果
score >= 0.9
将打印 'A' - 如果
score >= 0.8
将打印 'B' - 0.7,C
- 0.6,D
- 以及低于该点的任何值,打印 F
- If
score >= 0.9
would print 'A' - If
score >= 0.8
would print 'B' - 0.7, C
- 0.6, D
- And any value below that point, print F
这是构建它的方法,它适用于程序,但有点重复:
This is the way to build it and it works on the program, but it's somewhat repetitive:
if scr >= 0.9:
print('A')
elif scr >= 0.8:
print('B')
elif scr >= 0.7:
print('C')
elif scr >= 0.6:
print('D')
else:
print('F')
我想知道是否有一种方法可以构建一个函数,这样复合语句就不会重复.
I would like to know if there is a way to build a function so that the compound statements wouldn't be as repetitive.
我是一个完全的初学者,但会在以下几行:
I'm a total beginner, but would something in the lines of :
def convertgrade(scr, numgrd, ltrgrd):
if scr >= numgrd:
return ltrgrd
if scr < numgrd:
return ltrgrd
有可能吗?
这里的目的是稍后我们可以通过只传递 scr、numbergrade 和 letter grade 作为参数来调用它:
The intention here is that later we can call it by only passing the scr, numbergrade and letter grade as arguments:
convertgrade(scr, 0.9, 'A')
convertgrade(scr, 0.8, 'B')
convertgrade(scr, 0.7, 'C')
convertgrade(scr, 0.6, 'D')
convertgrade(scr, 0.6, 'F')
如果可以传递更少的参数,那就更好了.
If it would be possible to pass fewer arguments, it would be even better.
推荐答案
您可以使用 bisect 模块进行数字表查找:
You can use the bisect module to do a numeric table lookup:
from bisect import bisect
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect(breakpoints, score)
return grades[i]
>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']
这篇关于如何简化评分系统函数中重复的 if-elif 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!