以范围为键的字典 [英] Dictionary with range as key
本文介绍了以范围为键的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,如何将一系列值映射到一个具体值? 基本上,我想要一本字典,可以用数字填充范围和索引:
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
推荐答案
感谢注释,我可以使用intervaltree
包找到解决方案.
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]
这篇关于以范围为键的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文