一组非重叠整数范围的 Python 表示

标签 python

我想使用 Python 表示一组整数范围,其中可以动态修改该集合并测试其是否包含在内。具体来说,我想将其应用于文件中的地址范围或行号。

我可以定义我关心的地址范围:

200 - 400  
450 - 470  
700 - 900  

然后我希望能够向集合中添加一个可能重叠的范围,这样当我添加 460 - 490 时,集合变为:

200 - 400  
450 - 490  
700 - 900  

然后可以从我可以排除范围 300 - 350 的集合中删除,集合变为:

200 - 300
350 - 400  
450 - 490  
700 - 900  

最后,我希望能够遍历集合中包含的所有整数,或者测试集合是否包含特定值。

我想知道执行此操作的最佳方法是什么(特别是如果 Python 中内置了一些东西)。

最佳答案

您正在描述一个 interval tree .

pip install intervaltree

用法:

from intervaltree import IntervalTree, Interval
tree = IntervalTree()
tree[200:400] = True  # or you can use ranges as the "values"
tree[450:470] = True
tree[700:900] = True

查询:

>>> tree
IntervalTree([Interval(200, 400, True), Interval(450, 470, True), Interval(700, 900, True)])
>>> tree[250]
{Interval(200, 400, True)}
>>> tree[150]
set()

添加重叠范围:

>>> tree[450:490] = True
>>> tree
IntervalTree([Interval(200, 400, True), Interval(450, 470, True), Interval(450, 490, True), Interval(700, 900, True)])
>>> tree.merge_overlaps()
>>> tree
IntervalTree([Interval(200, 400, True), Interval(450, 490), Interval(700, 900, True)])

丢弃:

>>> tree.chop(300, 350)
>>> tree
IntervalTree([Interval(200, 300, True), Interval(350, 400, True), Interval(450, 490), Interval(700, 900, True)])

关于一组非重叠整数范围的 Python 表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50592912/

相关文章:

python - 使用 fetchall() 将 MySQL 表转换为 Python 列表列表

python - urllib2.HTTPError : HTTP Error 403: Forbidden

python - 如何在 SQLAlchemy 中使用数学方程作为过滤器

python - 我的系统中的 PATH 与 "os"模块中的路径不匹配

python - 在 Python 中从 RTSP 流中读取帧

python - 如何使用 Zeep 准备 SOAP 请求?

python - 如何找到列表列表的所有可能组合(在 Python 中)?

python - ** 之后的参数必须是映射,而不是 SQLAlchemy 数据库中的 str

python - Beautiful Soup 在 """和 "<"等特殊字符上崩溃

python - numpy matrix trickery - 逆时矩阵之和