如何在评分系统功能中简化重复的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:
- 如果
得分> = 0.9
将显示'A' - 如果
得分> = 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屋!