使用python|使用python 进行区间取值的方法

需求背景:
进行分值计算。如下图,如果只是一两个还好说,写写判断,但是如果有几十个,几百个,会不会惨不忍睹。而且,下面的还是三种情况。
例如:
使用python|使用python 进行区间取值的方法
文章图片
使用python|使用python 进行区间取值的方法
文章图片

解决:

# 根据值、比较list, 值list,返回区间值, other_value 即不在的情况def get_value_by_between(self, compare_value, compare_list, value_list, other_value, type="compare", left=False,right=True):try:if compare_value is None or compare_value =https://www.it610.com/article/='':return other_value if len(compare_list) != len(value_list):raise Exception("区间对比两个list长度不一致") # # 如果比较的值和其它情况值一致,说明是其它情况# if compare_value =https://www.it610.com/article/= other_value:#return other_value # 左边开区间if compare_list[0] == -9999999 and compare_list[1]>= compare_value:return value_list[0] # 右边开区间if right is True and compare_value > compare_list[len(compare_list) - 1]:return value_list[len(compare_list) - 1]# 左边开区间# if left is True and compare_value <= compare_list[0]:#return compare_value[0] for ind, this_val in enumerate(compare_list):# 如果是最后一个,则返回最后一个值if compare_value > compare_list[len(compare_list) - 1]:return value_list[len(compare_list) - 1]# 返回默认的elif (ind + 1) == len(compare_list):return other_value # 下一个,如果大于compare_list长度减1 ,就返回最后一个next_val = compare_list[ind if ind >= len(compare_list) else ind + 1]# 第一个的话就是 大于等于,小于下一个if ind == 0 and compare_value >= this_val and compare_value <= next_val:return value_list[ind]# 大于左边,小于等于右边elif this_val < compare_value and compare_value <= next_val:return value_list[ind]except:log.error("根据区间计算分数异常", traceback.format_exc())return other_value

# 数字型def get_val_by_list(self, compare_value, compare_list, val_list, other_value):try:if compare_value is None:return other_value for ind, li in enumerate(compare_list):if len(li) == 1 and compare_value =https://www.it610.com/article/= li[0]:return val_list[ind]# 最后一个elif len(li) == 1 and (ind + 1) == len(compare_list) and compare_value>= li[0]:return val_list[ind]elif len(li) == 2 and compare_value >= li[0] and compare_value <= li[1]:return val_list[ind]except:log.error(" get_val_by_list 异常", traceback.format_exc())return other_value

TEST
# creditTime 即值self.get_val_by_list(creditTime, [[0],[1],[2],[3]], [20, 10, 0, -100],other_value=https://www.it610.com/article/0)

self.get_value_by_between(taxCreditRating, [0, 60, 70, 80, 90],[-200, 0, 10, 20, 30], other_value=https://www.it610.com/article/0)

如果是图2,即第三种情况,则需要多加一个0,和对应的值。
self.get_value_by_between(taxAmt12m, [0,0, 1000, 15000, 50000, 200000],[-50, -50, 0, 0, 5, 10], -0)

如果是负无穷大,则使用-999999
【使用python|使用python 进行区间取值的方法】到此这篇关于使用python 进行区间取值的文章就介绍到这了,更多相关python区间取值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读