[英]Simple way to stop a number going negative
我有一個簡單的練習。 我需要彼此減去2個元組,但我不希望結果為負,我想在0處停止。類似地,我想添加2個元組,但我想將該值的上限限制為255。
所以當我做(1,1,1)-(5,200,30)
我應該得到結果(0,0,0)
。 如果我做到(200,10,150)+(90,20,50)
我應該得到(255,30,200)
。
math
或numpy
中是否有任何便利函數可以做到這一點?
在numpy
檢查clip
np.clip(np.array((1,1,1))-np.array((5,200,30)),a_min=0,a_max=255)
Out[186]: array([0, 0, 0])
您可以執行類似選擇最大值(結果或0)的操作。 這樣,如果結果為負數,它將返回0。 例如:
t1 = (1,1,1)
t2 = (5, 200, 30)
減法
[max(x[0]-x[1], 0) for x in zip(t1, t2)]
補充
[min(x[0]+x[1], 255) for x in zip(t1, t2)]
def add(t1,t2):
"""
input: t1,t2 are tuples.
example t1(1,2,3) t2(7,8,9)
result=(a=1+7,b=2+8,c=3+9)
max of a, b, and c are 255
"""
a=t1[0]+t2[0]
b=t1[1]+t2[1]
c=t1[2]+t2[2]
if(a>255):
a=255
if(b>255):
b=255
if(c>255):
c=255
result=(a,b,c)
return result
#CALLING
x=(1,1,1)
y=(5,200,30)
z=(200,10,150)
t=(90,20,50)
print(add(z,t))
(255, 30, 200)
截取值的純python方法如下:
>>> x = (25, 400, 30)
>>> tuple(map(min, zip(x, (255,255,255))))
(25, 255, 30)
同樣的下限:
>>> x = (25, -20, 30)
>>> tuple(map(max, zip(x, (0,0,0))))
(25, 0, 30)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.