如果使用elif语句,该如何重构?

时间:2019-05-27 13:45:57

标签: python

有成绩清单-[a,b,c,d,e,f]

grade = int(input())
if grade >= 90 and grade <= 100:
    print('a')
elif grade >=70 and grade <= 80:
    print('b')
elif grade >=60 and grade <= 70:
    print('c')
elif grade >= 50 and grade <= 60:
    print('d')
elif grade < 50:
    print('e')

如何用2-3行代码优雅地重写它?

比如,有词典,其关键等级为'a','b','c','d',并且根据等级进行打印?

4 个答案:

答案 0 :(得分:4)

grades =  {'a': range(90,100), 'b': range(80,90),'c': range(70,80), 'd': range(60,70), 'e': range(50,60)}

grade = int(input())

for key,value in grades.items():
    if grade in value:
        print (key)

或仅使用列表理解:

grades =  {'a': range(90,100), 'b': range(80,90),'c': range(70,80), 'd':range(60,70), 'e': range(50,60)}

grade = int(input())

print ([key for key,value in grades.items() if grade in value][0])

答案 1 :(得分:2)

您可以zip评分和门槛:

grades = "edcba"
limits = [50, 60, 70, 80, 100]  # I think that 80-90 gap is not intentional
grade = int(input())
for limit, letter in zip(limits, grades):
    if grade <= limit:
        print(letter)
        break
else:
    print("Not found!")

答案 2 :(得分:1)

您可以通过以下措辞轻松摆脱范围检查的一半:

grade = int(input())
if grade < 50:
    print('e')
elif grade <= 60:
    print('d')
elif grade <= 70:
    print('c')
elif grade <= 80:
    print('b')
elif grade >= 90 and grade <= 100:
    print('a')
else
    print('unknown')

我不确定您的90 <= grade <= 100范围是否正确,或者您是否打算将其与先前的下一个范围相邻。无论如何,它并没有改变我建议的重构。

答案 3 :(得分:-1)

您可以将成绩存储在这样的列表中

grades = "e d c b a".split()

grades = ['e', 'd', 'c', 'b', 'a']

类似地,您可以存储分数阈值,超过该阈值将导致成绩升级

marks = [59, 69, 79, 89]

现在您将需要为标记建立索引

for i, score in enumerate(marks):
    if grade > score:
        index = i

或可以使用较小的方法

index = sum([grade > score for score in marks])

最后,打印所需的值

print(grades[index])

因此,最终代码应类似于

grade = int(input)
grades = ['e', 'd', 'c', 'b', 'a']
marks = [59, 69, 79, 89]
print(grades[sum([grade > score for score in marks])])

更小的实现(逐行)

grade, grades, marks = int(input), ['e', 'd', 'c', 'b', 'a'], [59, 69, 79, 89]
print(grades[sum([grade > score for score in marks])])