需求配景:
进行分值盘算。如下图,假如只是一两个还好说,写写判定,但是假如有几十个,几百个,会不会惨不忍睹。而且,下面的照旧三种情况。
比方:
办理:
- # 根据值、比较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 == '':
- return other_value
-
- if len(compare_list) != len(value_list):
- raise Exception("区间对比两个list长度不一致")
-
- # # 如果比较的值和其它情况值一致,说明是其它情况
- # if compare_value == 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 == 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=0)
复制代码
- self.get_value_by_between(taxCreditRating, [0, 60, 70, 80, 90],[-200, 0, 10, 20, 30], other_value=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区间取值内容请搜索脚本之家以前的文章或继承欣赏下面的干系文章盼望各人以后多多支持脚本之家! |