Dictionary with range as key

孤人 提交于 2019-12-19 17:14:29

问题


In Python, how can I map from a range of values to one concrete value? Basically, I want a dictionary, which I can fill with ranges and index with numbers:

rd = rangedict()
rd[(0, 10)] = 5
print rd[4] # prints 5
print rd[6] # prints 5
rd[(5, 15)] = 20
print rd[4] # prints 5
print rd[6] # prints 20

回答1:


You could use an interval tree

pip install intervaltree

from intervaltree import Interval, IntervalTree
rd = IntervalTree()

rd[0:10] = 5
print rd[4]
print rd[5]

https://pypi.python.org/pypi/intervaltree




回答2:


Thanks to the comments I could find a solution using the intervaltree package.

from intervaltree import IntervalTree

tree = IntervalTree()
tree.addi(0, 10, 5)
print tree[4]
print tree[6]

# need to chop before, as the library stores both intervals otherwise
tree.chop(5, 15)
tree.addi(5, 15, 20)
print tree[4]
print tree[6]


来源:https://stackoverflow.com/questions/34717934/dictionary-with-range-as-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!