Python 3.8版本引入了一项新的语言特性——海象运算符(walrus operator)。它通过使用":="符号,允许我们在表达式中赋值并使用该值。这个简单而强大的运算符为开发者提供了一种更便捷、更高效的编程方式。

之所以叫这个名字,源于它看起来像海象的牙和鼻孔。

在引入海象运算符之前,我们通常需要在使用之前为变量赋值。这在某些情况下会导致冗长的代码,尤其是在需要在表达式中使用赋值结果时。海象运算符的出现解决了这个问题,它允许我们在表达式中直接进行赋值操作,提高了代码的简洁性和可读性。

下面我们来看看海象运算符的各种应用场景。

打印

在不使用海象运算符的情况下,如果要给一个变量赋值,并同时打印这个变量,需要下面两行代码:

a = 1
print(a)

有了海象运算符,他们可以被合并为一行:

print(a := 1)

海象运算符允许我们把 1 赋值给变量 a 同时打印 a。

读取输入

在下面的示例中,我们在 while 循环中使用海象运算符。

假设现在要从用户的输入中读取内容,知道用户输入的是quit停止。我们的代码可以写成这样:

words = []

while True:
word = input("Enter word: ")
if word == "quit":
break
words.append(word)

print(words)

使用海象运算符,可以简化为这样:

#!/usr/bin/python

words = []

while (word := input("Enter word: ")) != "quit":
words.append(word)

print(words)

if 条件下使用

假设我们要求所有的单词必须至少有三个字符:

words = ['falcon', 'sky', 'ab', 'water', 'a', 'forest']

for word in words:
n := len(word)
if n < 3:
print(f'warning, the word {word} has {n} characters')

使用海象运算符,可以简化为下面:

words = ['falcon', 'sky', 'ab', 'water', 'a', 'forest']

for word in words:
if ((n := len(word)) < 3):
print(f'warning, the word {word} has {n} characters')

海象运算符在表达式中的使用可以简化复杂的计算逻辑,并提高代码的可读性。

读取文件

海象运算符在处理文件时非常有用,特别是在需要逐行读取文件并对每一行进行处理的情况下。使用海象运算符,我们可以将读取的行赋给一个变量,并在处理完该行之后再读取下一行:

with open('words.txt', 'r') as f:
while line := f.readline():
print(line.rstrip())

海象运算符使代码更短。

遍历容器

在下面的示例中,我们遍历字典。

users = [ 
{'name': 'John Doe', 'occupation': 'gardener'},
{'name': None, 'occupation': 'teacher'},
{'name': 'Robert Brown', 'occupation': 'driver'},
{'name': None, 'occupation': 'driver'},
{'name': 'Marta Newt', 'occupation': 'journalist'}
]

for user in users:
if ((name := user.get('name')) is not None):
print(f'{name} is a {user.get("occupation")}')

正则表达式

正则表达式是海象运算符的一个重要应用场景。

假设我们要在一个大文件中搜索每一行,如果有匹配模式的内容,则将其挑选出来。按照传统做法,可以写为:

for line in lines:
strs = re.findall(pattern, line)
if strs:
print(strs)

可以被简化为:

for line in lines:
if strs := re.findall(pattern, line)
print(strs)

注意事项

  • 不能直接使用海象运算符赋值,像这样的赋值:
a := 10

是错误的语法。

  • 海象运算符只能在Python 3.8及更高版本中使用。
  • 应避免在复杂的表达式中过度使用海象运算符,以免影响代码的可读性。
  • 在循环条件中使用海象运算符时,需要确保赋值操作不会对性能产生显著影响。
举报/反馈

一姐韩梅

2048获赞 362粉丝
读过1000本书 ,泛知识类文章都写。
关注
0
0
收藏
分享