编写约束函数的最佳方法是什么?或者是否已经有内置的python函数来执行此操作?
选项1:
def constrain(val, min_val, max_val):
if val < min_val: return min_val
if val > max_val: return max_val
return val
选项2:
def constrain(val, min_val, max_val):
if val < min_val:
val = min_val
elif val > max_val:
val = max_val
return val
答案 0 :(得分:12)
我不知道这是否更“pythonic”,但你可以像这样使用内置的min()
和max()
:
def constrain(val, min_val, max_val):
return min(max_val, max(min_val, val))
答案 1 :(得分:5)
答案 2 :(得分:0)
如果您可以一次处理一堆值,则可以尝试列表推导:
a = [1,1,5,1,1]
b = [7,2,8,5,3]
c = [3,3,3,3,3]
[min(y,max(x,z)) for x,y,z in zip(a, b, c)]
[3, 2, 5, 3, 3]
甚至是NumPy:
import numpy as np
a = np.array(a)
b = np.array(b)
c = np.array(c)
np.minimum(b, np.maximum(a, c))
np.minimum(b, np.maximum(a, 3)) # just use 3 if they are all the same
c.clip(a, b) # or just use NumPy's clip method
np.clip(c, a, b)
array([3, 2, 5, 3, 3])
array([3, 2, 5, 3, 3])
array([3, 2, 5, 3, 3])
array([3, 2, 5, 3, 3])