pythonpython-3.xdictionary

best way to map a value from range number in python?


Say we have a data example like this:

AQI LEVEL
0~50 1
51~100 2
101~150 3
151~200 4
201~300 5
>300 6

What's the best way to return the Level of AQI by given a AQI value(ex:100, return 2)

def get_level_of_aqi(aqi):
    # do sth map idea like here
    return level_of_aqi

My current method:

def get_level_of_aqi(aqi):
    if 0 <= aqi <= 50:
        level = 1
    elif 51 <= aqi <= 100:
        level = 2
    ....

    return level

Is there any better way to improve ?


Solution

  • Given that the ranges aren't all equal sizes (for 1-4, the range is 50, but for 5 it is 100), you could use a generator expression with sum() like this:

    def get_level_of_aqi(aqi):
        return sum(l<=aqi for l in [0, 51, 101, 151, 201, 301])
    

    This takes advantage of True having a value of 1 and False having a value of 0

    Here are example outputs:

    In [1]: get_level_of_aqi(50)
    Out[1]: 1
    
    In [2]: get_level_of_aqi(100)
    Out[2]: 2
    
    In [3]: get_level_of_aqi(125)
    Out[3]: 3
    
    In [4]: get_level_of_aqi(220)
    Out[4]: 5
    
    In [5]: get_level_of_aqi(280)
    Out[5]: 5
    
    In [6]: get_level_of_aqi(310)
    Out[6]: 6