Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More pythonic alternative for getting a value in range not using min and max [closed]

Tags:

python

I have this:

a = min(max(x, 1), 100)

Is there anything more pythonic?

like image 954
Schultz9999 Avatar asked Apr 24 '15 22:04

Schultz9999


3 Answers

What about:

a = 1 if x < 1 else 10 if x > 10 else x

It gives the readability that you wanted without the redundancy of the version in your comment. It is verbose because it defines the centre case first and then has to distinguish between the two ends. This way of doing it cuts the ends of first and everything left is in range.

like image 191
neil Avatar answered Nov 04 '22 05:11

neil


If it's for an array, you could use numpy.clip.

Otherwise, I think your solution is the best one. Or you could define your own function that does the same for a single element, if you do that at multiple places.

like image 4
Valentin Lorentz Avatar answered Nov 04 '22 06:11

Valentin Lorentz


Another option that you might consider more pythonic:

if x > 100:
    x = 100
elif x < 1:
    x = 1
like image 2
Ella Sharakanski Avatar answered Nov 04 '22 05:11

Ella Sharakanski