找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 2450|回复: 2

[已解决] 按整数范围映射为字符问题

1

主题

1

帖子

1

积分

贫民

积分
1
毅翔 发表于 2017-9-11 18:45:26 | 显示全部楼层 |阅读模式
本帖最后由 毅翔 于 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


点评

不错!  发表于 2017-9-11 19:57
回复

使用道具 举报

0

主题

7

帖子

7

积分

贫民

积分
7
unintelligible 发表于 2017-9-19 11:41:36 | 显示全部楼层
dict1={9050:"A",5050:'B',450:"C",-600:"D"}
score=-50000
info = 'error'
for i in sorted(dict1.keys(),reverse=True):
    if score >= i:
        info= dict1
        break
print info


我觉得应该可以,欢迎回复
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表