:= 海象運算符,可在表達式內部為變量賦值。Python3.8 版本新增運算符。
在這個示例中,賦值表達式可以避免調用 len() 兩次,從而提高了運行速度:
if (n := len(a)) > 10: print(f"List is too long ({n} elements, expected <= 10)")
假如在沒有海象運算符的時候,我們會怎么來寫這段代碼呢?來試一試:
if len(a) > 10: print(f"List is to long({len(a)} elements, expected <= 10)")
或者這樣寫,避免使用兩次len方法,卻又多了一次賦值給中間變量的步驟.
n = len(a) if n > 10: print(f"List is to long({n} elements, expected <= 10)")