[英]Get a value between min and max values in Python
I wan't to get a value if it's between min and max values. 如果它在最小值和最大值之间,我不会得到一个值。 If the value is smaller than min, I want to get the min value and if it's greater than max I want to get the max. 如果该值小于min,我想得到最小值,如果它大于max,我想得到最大值。 I use this code now, but is there an inbuilt or smarter way to do it? 我现在使用这个代码,但是有一种内置或更智能的方法吗?
def inBetween(minv, val, maxv):
if minv < val < maxv: return val
if minv > val: return minv
if maxv < val: return maxv
print inBetween(2,5,10)
For the record: This kind of function is usually called clamp
(as in clamping ), sometimes clip
. 记录:这种功能通常称为clamp
(如钳位 ),有时也称为clip
。 The signature you mostly find for this is clamp(val, minv, maxv)
. 你clamp(val, minv, maxv)
找到的签名是clamp(val, minv, maxv)
。 If you don't like the idiomatic solution using the functions min
and max
because of the function overhead, you may use this solution: 如果由于函数开销而不喜欢使用函数min
和max
的惯用解决方案,则可以使用此解决方案:
def clamp(val, minv, maxv):
return minv if val < minv else maxv if val > maxv else val
A quick'n'dirty performance check: 一个快速的性能检查:
>>> import timeit
>>> timeit.timeit("clamp(1, 5, 10)", "def clamp(val, minv, maxv): return min(maxv, max(minv, val))")
1.8955198710000332
>>> timeit.timeit("clamp(1, 5, 10)", "def clamp(val, minv, maxv): return minv if val < minv else maxv if val > maxv else val")
0.5956520039999305
Put them in a list, sort the list, chose middle element. 将它们放在列表中,对列表进行排序,选择中间元素。
>>> def inbetween(minv,val,maxv):
... return sorted([minv,val,maxv])[1]
...
>>> inbetween(2,5,10)
5
>>> inbetween(2,1,10)
2
>>> inbetween(2,11,10)
10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.