官网介绍:Assignment expressions(赋值表达式)
python 3.8 新特性网址:https://docs.python.org/3/whatsnew/3.8.html
对比下面同一种功能,三种写法:
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
#避免调用两次len()
if len(a) > 10:
print(f"List is to long({len(a)} elements, expected <= 10)")
#这里要多次使用 len(a)
n = len(a)
if n > 10:
print(f"List is to long({n} elements, expected <= 10)")
#这里多了赋值语句