使用Python如何优雅地进行成绩等级判断?

一般想到的方法为:

# -*- coding:utf-8 -*-
# author: Man Yacan
# Email: myxc@live.cn
# Website: https://www.manyacan.com
# datetime: 2020/9/2 20:39
# software: PyCharm


score = int(input("请输入成绩:"))  # 输入成绩

# 进行成绩判断
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'E'

print(f"成绩等级为{grade}")  # 打印成绩等级

但是这种方法重复代码太多,十分不优雅。

Python没有像JavaScript或者PHP那样的switch语句,那么该如何实现呢?

今天在网上看到一段代码,十分优雅的实现了成绩等级判断。

# -*- coding:utf-8 -*-
# author: Man Yacan
# Email: myxc@live.cn
# Website: https://www.manyacan.com
# datetime: 2020/9/2 20:39
# software: PyCharm

from bisect import bisect


def score_grade(score):
    breakpoints = [60, 70, 80, 90]
    grades = "EDCBA"
    i = bisect(breakpoints, score)
    return grades[i]


print(score_grade(int(input("请输入成绩:"))))

笔记

了解bisect类,这个类可以使用二分法在已经过排序的数组中查找元素的位置,返回该值在list中的位置,说不清,直接上代码:

from bisect import bisect, insort

breakpoints = [60, 70, 80]

insort(breakpoints, 90)

print(str(breakpoints))  # [60, 70, 80, 90]

print(bisect(breakpoints, 60))  # 1
print(bisect(breakpoints, 90))  # 4

print(bisect(breakpoints, 61))  # 1
print(bisect(breakpoints, 82))  # 3
数组在使用该方法前必须先完成排序,可以使用.sort()
In [2]: a = [1, 0, 3, 4, 7, 5]

In [3]: a.sort()

In [4]: a
Out[4]: [0, 1, 3, 4, 5, 7]