海象运算符
最近,在刷Leetcode时,看到了一个新的运算符:
if (n := len(a)) >= 10:
print('true')
一开始还不明白,后来一查,原来是Python3.8中新加入的赋值表达式。
可以看出Python3.7并不支持
官网是这样介绍这个新的赋值表达式的:
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.
我来概括一下: 这个表达式允许把表达式的一部分赋值给变量,也就是可以省去一个赋值变量的过程。
下面让我们来用代码来说明一下:
a = 'HELLO'
if (n := len(a)) >= 10:
print('true')
结果为:
而如果我们不用海象运算符,怎么写这段代码?
a = 'HELLO HELL0'
#
# if (n := len(a)) >= 10:
# print('true')
n = len(a)
if n >= 10:
print('ture')
所以,这样就可以看出海象运算符的优点: 可以为我们省去一个赋值的步骤,使代码更简洁。