官网介绍:Assignment expressions(赋值表达式)
There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.
表达式的一部分赋值给变量
使用
示例1:
1 | n = len(a) |
使用海象运算符后,可以改写成以下形式:1
2if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
示例2:
1 | # Loop over fixed length blocks |