I have this:
a = min(max(x, 1), 100)
Is there anything more pythonic?
I have this:
a = min(max(x, 1), 100)
Is there anything more pythonic?
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.
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.
Another option that you might consider more pythonic:
if x > 100:
x = 100
elif x < 1:
x = 1
What about something a little different:
a = (1, x, 100)[-(x<1)+1+(x>100)]
or if you define your limits as
lo, hi = (1, 100)
a = (lo, x, hi)[-(x<lo)+1+(x>hi)]
Or rearrange your data, and it looks more elegant:
a = (x,lo,hi)[(x<lo)-(x>hi)]
This is possible in python because booleans behave like the values 0 and 1, allowing the math inside the []
to get the right index of the tuple.
a = x if x in range(1,100) else 1 if x < 1 else 100
Do you really need to floor at 1 and ceil at 100 ?