例如我们要把如下的一段代码给转换为非if…elif…elif…else…的代码结构
def convert_grade(scr):
if scr >= 90:
print('A')
elif scr >= 80:
print('B')
elif scr >= 70:
print('C')
elif scr >= 60:
print('D')
else:
print('F')
convert_grade(89)
方法一,利用列表
base_list = [(90, 'A'), (80, 'B'), (70, 'C'), (60, 'D')]
def convert_grade(scr):
for _scr, grade in base_list:
if scr >= _scr:
print(grade)
break
else:
print('F')
convert_grade(59)
方法二,利用bisect模块
from bisect import bisect
def convert_grade(scr, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect(breakpoints, scr)
return grades[i]
print([convert_grade(score) for score in [33, 99, 77, 70, 89, 90, 100]])
方法三,使用字典
grades = {
"A": 90, "B": 80, "C": 70, "D": 60}
def convert_grade(scr):
for grade, _src in sorted(grades.items()):
if scr >= _src:
return grade
return "F"
print(convert_grade(45))
def convert_grade(score):
"""Return a letter grade."""
grades = {
100: "A", 90: "A", 80: "B", 70: "C", 60: "D"}
return grades.get((score // 10) * 10, "F")
print([grade(scr) for scr in [100, 33, 95, 61, 77, 90, 89]])
方法四,使用zip(),next()
def convert_grade(scr):
grades = zip('ABCD', (90, 80, 70, 60))
return next((grade for grade, limit in grades if scr >= limit), 'F')
print(convert_grade(40))
方法五,利用math模块
from math import floor
def grade(mark):
return ["D", "C", "B", "A"][min(int(floor(mark / 10)) - 6, 3)] if mark >= 60 else "F"
print(grade(79))
类似话题