我想知道是否有壓縮這個代碼的方式:Python單線程確保0 <=值<= 1?
foo = calculate() # 'calculate' is some kind of function which
# could return float values less than 0.0 or more than 1.0
# It's here only as a (hopefully) clarification
bar = foo * 5
if bar < 0:
bar = 0
elif bar > 1:
bar = 1
else:
pass # 'bar' has a good value within the "range"
我知道我可以做bar = max(foo * 5, 0)
或bar = min(foo * 5, 1)
但...有沒有在只有一條線這樣的方式?像bar = ensure_between(0, foo * 5, 1)
或類似的東西?
這不是什麼大事,我只是好奇。
預先感謝您:-)
http://stackoverflow.com/questions/4092528/how-to-在Python中使用一個整數到一定範圍 – zch
你是不是指'elif foo * 5> 1:bar = 1'? –
@TigranSaluev是的,絕對!接得好。從實際的代碼到foobars的糟糕的翻譯:D對不起(編輯問題,因爲它應該已經完成) – BorrajaX