Python:从时间间隔到值的映射 [英] Python: Mapping from intervals to values

查看:98
本文介绍了Python:从时间间隔到值的映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构一个函数,给定一系列隐式定义间隔的端点,请检查该间隔中是否包含数字,然后返回对应的数字(以任何可计算的方式不相关). 现在正在处理工作的代码是:

I'm refactoring a function that, given a series of endpoints that implicitly define intervals, checks if a number is included in the interval, and then return a corresponding (not related in any computable way). The code that is now handling the work is:

if p <= 100:
    return 0
elif p > 100 and p <= 300:
    return 1
elif p > 300 and p <= 500:
    return 2
elif p > 500 and p <= 800:
    return 3
elif p > 800 and p <= 1000:
    return 4
elif p > 1000:
    return 5

这对IMO来说是非常可怕的,并且缺乏间隔和返回值都经过硬编码的缺点. 当然,可以使用任何数据结构.

Which is IMO quite horrible, and lacks in that both the intervals and the return values are hardcoded. Any use of any data structure is of course possible.

推荐答案

import bisect
bisect.bisect_left([100,300,500,800,1000], p)

此处提供文档: bisect

这篇关于Python:从时间间隔到值的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆