Python: Mapping from intervals to values

前端 未结 6 955
遥遥无期
遥遥无期 2020-11-30 00:58

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 correspondi

6条回答
  •  情深已故
    2020-11-30 01:34

    Try something along the lines of:

    d = {(None,100): 0, 
        (100,200): 1,
        ...
        (1000, None): 5}
    value = 300 # example value
    for k,v in d.items():
        if (k[0] is None or value > k[0]) and (k[1] is None or value <= k[1]):
            return v
    

提交回复
热议问题