Mapping a range of values to another

前端 未结 6 2223
谎友^
谎友^ 2020-11-28 02:39

I am looking for ideas on how to translate one range values to another in Python. I am working on hardware project and am reading data from a sensor that can return a range

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 02:55

    This would actually be a good case for creating a closure, that is write a function that returns a function. Since you probably have many of these values, there is little value in calculating and recalculating these value spans and factors for every value, nor for that matter, in passing those min/max limits around all the time.

    Instead, try this:

    def make_interpolater(left_min, left_max, right_min, right_max): 
        # Figure out how 'wide' each range is  
        leftSpan = left_max - left_min  
        rightSpan = right_max - right_min  
    
        # Compute the scale factor between left and right values 
        scaleFactor = float(rightSpan) / float(leftSpan) 
    
        # create interpolation function using pre-calculated scaleFactor
        def interp_fn(value):
            return right_min + (value-left_min)*scaleFactor
    
        return interp_fn
    

    Now you can write your processor as:

    # create function for doing interpolation of the desired
    # ranges
    scaler = make_interpolater(1, 512, 5, 10)
    
    # receive list of raw values from sensor, assign to data_list
    
    # now convert to scaled values using map 
    scaled_data = map(scaler, data_list)
    
    # or a list comprehension, if you prefer
    scaled_data = [scaler(x) for x in data_list]
    

提交回复
热议问题