|
本帖最后由 毅翔 于 2017-9-11 19:09 编辑
有大神知道python 有方法可以灵活的处理这种if else的方法吗?比如说不要score >= -600 and score < 200的判断等等
if score >= 9050:
level = 'A'
elif score >= 5050 and score < 9050:
level = 'B'
elif score >= 450 and score < 5050:
level = 'C'
elif score >= 351 and score < 450:
level = 'D'
elif score >= 200 and score < 351:
level = 'E'
elif score >= -600 and score < 200:
level = 'F'
else:
level = 'error'
小弟现在只想到用for循环去跑一个“一堆lambda函数作为key,value为字符串”这样的dictionary,然后返回一个计算结果为True对应的value。
score_input = 30
score_output = 'error'
score = {
lambda x: x < 22 or x >= 50: 'A',
lambda x: 22 <= x < 25: 'B',
lambda x: 25 <= x < 30: 'C',
lambda x: 30 <= x < 35: 'D',
lambda x: 35 <= x < 45: 'E',
lambda x: 45 <= x < 50: 'F',
}
for func in score.keys():
if func(score_input):
score_output = score[func]
因为涉及大量的这样的处理,求助各位大神,有没有更加简易的方法去进行处理
群里王亮大神解决了bins = [-600,200,351,450,9050]
labels = ['F', 'E', 'D','C' ]
a = [0, 100, 400, 800]
pd.cut(a, bins, labels=labels) # pd 是pandas
|
|