Python: Mapping from intervals to values(Python:从间隔映射到值)
本文介绍了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:从间隔映射到值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Python:从间隔映射到值
基础教程推荐
猜你喜欢
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01