clip_values
1.0.0
clip_values 剪輯數值以確保它們在下限和上限內是非常普遍的任務。
例如,如果您要處理RGB顏色,則希望每個頻道在0到255之間,如果您要處理商店的銷售,則需要它們在0到1之間,或者如果您正在編寫很酷的遊戲,則希望您的角色留在屏幕中。
現在,如果您必須進行所有這些剪輯,那麼您喜歡哪種替代方法?
clip_values.clip clip為您的剪輯操作提供人類可讀的語法:
from clip_values import clip
colour_channel = clip ( colour_channel ). between_ ( 0 ). and_ ( 255 )
discount = clip ( discount ). between_ ( 0 ). and_ ( 1 )
player_x_pos = clip ( player_x_pos ). between_ ( 0 ). and_ ( SCREEN_WIDTH ) clip替代方案是最簡單,最容易閱讀的!將其與另外兩個常見替代方案進行比較:
使用if: ... elif: ... block也很容易閱讀,但佔用4倍的代碼行:
if colour_channel < 0 :
colour_channel = 0
elif colour_channel > 255 :
colour_channel = 255
if discount < 0 :
discount = 0
elif discount > 1 :
discount = 1
if player_x_pos < 0 :
player_x_pos = 0
elif player_x_pos > SCREEN_WIDTH :
player_x_pos = SCREEN_WIDTH用max鏈min (或相反的方式)縮短了,但這很難閱讀,您必須花幾分鐘時間來弄清兩次連續的電話之間的互動,以達到min / max :
colour_channel = min ( 255 , max ( 0 , colour_channel ))
discount = max ( 0 , min ( 1 , discount ))
player_x_pos = min ( SCREEN_WIDTH , max ( 0 , player_x_pos ))