Pyderman
Pyderman

Reputation: 16189

Python dict: How to map keys to values, where key is a range?

I have a list of values:

[0,1.51, 2.01, 2.51, 3.01,5.01, 6.01,7.01, 8.01,9.01, 10.01]

And a second list of values:

[.15, .22, .3, .37, .4, .5, .6, .7, .8, .9, 1]

The rough logic of my programme is that if the value of some variable falls between two values in the first list, then set the value of another variable to the corresponding item in the second list i.e.

if 0 < x < 1.51:
    y = 0.15
elif 1.51 < x < 2.01:
    y = .22
and so on

Obviousy I could extend the if/elif/else flow to cover each case, but (i) this is not pretty, (ii) it's not sustainable (iii) I want to be able to apply this to any two lists, not neededing to know any of the values contained within.

What's are the best ways of achieving this in Python?

Many thanks

Upvotes: 0

Views: 962

Answers (2)

raton
raton

Reputation: 428

    m=[0,1.51, 2.01, 2.51, 3.01,5.01, 6.01,7.01, 8.01,9.01, 10.01]
    n=[.15, .22, .3, .37, .4, .5, .6, .7, .8, .9, 1]



    def test(x,a,b):
       for i in range(len(a)-1):
             if a[i] < x <a[i+1]:return b[i]

    >>>>test(3,m,n)
    >>>> 0.37
    >>>>test(.32,n,m)
    >>>> 2.01

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142136

Have a look at the bisect module - http://docs.python.org/2/library/bisect.html

And the example there for percentage->grades:

>>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
        i = bisect(breakpoints, score)
        return grades[i]

>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']

Upvotes: 7

Related Questions