Python 中 walrus 操作符
Python 3.8 引入的海象操作符 :=(赋值表达式)的作用是什么?请举例说明使用场景。
回答
古法程序员
:= 允许在表达式中同时赋值和返回结果,减少重复计算。
# 场景1: 避免重复调用
if (n := len(data)) > 10:
print(f'Long data: {n} items')
# 不用 walrus:n = len(data); if n > 10: ...
# 场景2: while 循环中
while (line := file.readline()):
process(line)
# 场景3: 列表推导式中
results = [y for x in data if (y := transform(x)) is not None]
# 场景4: 正则匹配
import re
if (match := re.search(pattern, text)):
print(f'Found: {match.group()}')
注意事项:
- 不要过度使用,避免降低可读性
- 优先级较低,复杂表达式需加括号
- 不能在表达式中反复赋值(如
a := b := 5非法) - 不能用于赋值语句的位置(如
a := 5, b := 6非法)