Python3.8新特性 | 赋值表达式——海象操作符(:=)

Python3.8加入了一种新的语法:=,它把值付给变量然后作为较大表达式的一部分。把:=成为海象操作符是因为这个符号长得像海象的眼睛和獠牙。

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.


下面这个例子,把赋值表达式作为if语句的一部分,避免了两次调用len()函数:

if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

在正则表达式匹配期间,通常需要使用匹配的对象两次,一次用于测试是否发生匹配,另一次用于提取子组,这时候使用:=赋值表达式也能达到很好的效果,避免重复代码:

discount = 0.0
if (mo := re.search(r'(\d+)% discount', advertisement)):
    discount = float(mo.group(1)) / 100.0

:=赋值表达式还可以用在whiel循环语句中,一个变量既用于测试循环终止,有在循环体中使用,这时候:=赋值表达式就有用处:

# Loop over fixed length blocks
while (block := f.read(256)) != '':
    process(block)

这种情形在旧版本中,通常使用break关键字:

while True:
    block = f.read(256)
    if block == '':
        break
    process(block)

在带有过滤条件的列表生成式中使用:=赋值是代码降低复杂度,可读性更强:

[clean_name.title() for name in names
 if (clean_name := normalize('NFC', name)) in allowed_names]

旧版实现:

[normalize('NFC', name).title() for name in names
 if normalize('NFC', name) in allowed_names]
 # 调用两次normalize方法

不断增加语法糖使Python代码越发简洁了,花点时间学习^_^

你可能感兴趣的:(Python3.8新特性 | 赋值表达式——海象操作符(:=))