omar.khairat
omar.khairat

Reputation: 117

python rank a value from list out of the list percentile using lambda

suppose I have a list of numbers and I applied percentile on this list which returns the following dictionary

{100: 2004807.0, 75: 11600.0, 50: 2559.5, 25: 316.0}

and then I have created the following function to return the corresponding value of a percentage

def f(x):
    return {
        25: 316.0,
        50: 2559.5,
        75: 11600.0,
        100: 2004807.0
    }[x]

now the following function returns the rank of a value

def rank(y):
    if y <= f(25):
        return 25
    elif y <= f(50):
        return 50
    elif y <= f(75):
        return 75
    else:
        return 100

is this doable using python lambda ?

Upvotes: 1

Views: 287

Answers (2)

jpp
jpp

Reputation: 164693

You can construct a list from your dictionary sorted by value. This conversion is necessary because dictionaries are not ordered, unless you are using Python 3.7+.

Then use next and a generator expression within your lambda:

d = {100: 2004807.0, 75: 11600.0, 50: 2559.5, 25: 316.0}
d_rev = sorted(d.items(), key=lambda x: x[1])

val = 2000
res = (lambda x: next((k for k, v in d_rev if x <= v), 100))(val)

print(res)
# 50

Upvotes: 1

Taku
Taku

Reputation: 33724

Without changing the f() function, I would use next with a generator whilst providing a default of 100.

lambda y: next((x for x in [25, 50, 75] if y <= f(x)), 100)

Upvotes: 1

Related Questions