ZetCode

Python 海象运算符

最后修改于 2024 年 1 月 29 日

Python 海象运算符教程展示了如何在 Python 中使用海象运算符。

Python 3.8 引入了一个新的海象运算符 :=。 该运算符的名称来源于它看起来像海象侧面的眼睛和獠牙。

海象运算符创建一个赋值表达式。 该运算符允许我们在 Python 表达式内部将一个值赋给一个变量。 这是一个方便的运算符,可以使我们的代码更紧凑。

print(is_new := True)

我们可以一步完成变量的赋值和打印。

is_new = True
print(is_new)

如果没有海象运算符,我们需要创建两行代码。

Python 海象运算符读取输入

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

read_words.py
#!/usr/bin/python

words = []

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

print(words)

我们要求用户输入单词,这些单词会被追加到一个列表中。

$ ./read_words.py
Enter word: cloud
Enter word: falcon
Enter word: rock
Enter word: quit
['cloud', 'falcon', 'rock']

Python 海象运算符与 if 条件一起使用

假设我们所有的单词都必须至少包含三个字符。

test_length.py
#!/usr/bin/python

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')

在此示例中,我们使用海象运算符来测试单词的长度。 如果一个单词的长度小于三个字符,则会发出警告。 我们一步确定并分配单词的长度。

$ ./test_length.py
warning, the word ab has 2 characters
warning, the word a has 1 characters

Python 海象运算符读取文件

在下一个示例中,我们使用海象运算符来读取文件。

words.txt
falcon
sky
cloud
water
rock
forest

我们在 words.txt 文件中包含一些单词。

read_file.py
#!/usr/bin/python

with open('words.txt', 'r') as f:

    while line := f.readline():

        print(line.rstrip())

该示例使用 readline 方法读取文件。 海象运算符使代码更短。

Python 海象运算符遍历容器

在以下示例中,我们在遍历字典列表时使用海象运算符。

traversing.py
#!/usr/bin/python

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")}') 

在此示例中,我们的字典中包含 None 值。 我们打印所有指定了名称的用户。

$ ./traversing.py
John Doe is a gardener
Robert Brown is a driver
Marta Newt is a journalist

有三个用户指定了他们的姓名。

Python 海象运算符与正则表达式一起使用

在以下示例中,我们在正则表达式中使用海象运算符。

search.py
#!/usr/bin/python

import re

data = 'There is a book on the table.'

pattern = re.compile(r'book')

if match := pattern.search(data):
    print(f'The word {pattern.pattern} is at {match.start(), match.end()}') 
else:
    print(f'No {pattern.pattern} found')

我们搜索一个模式,并将匹配项(如果找到)一步赋值给一个变量。

$ ./search.py
The word book is at (11, 15)

在给定的索引处找到了单词 book。

来源

Python 语言参考

在本文中,我们使用了 Python 海象运算符。

作者

我叫 Jan Bodnar,是一名充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程