Python 赋值表达式

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将学习 Python 的赋值表达式(Assignment Expressions),也称为“海象运算符”(:=)。该运算符在 Python 3.8 中引入,允许你在表达式中为变量赋值。它特别适用于优化代码、避免冗余计算以及简化复杂表达式。

通过本实验的学习,你应该能够理解并在你的 Python 程序中应用赋值表达式。我们将从简单的示例开始,逐步过渡到更复杂的案例。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/while_loops("While Loops") python/ControlFlowGroup -.-> python/list_comprehensions("List Comprehensions") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/scope("Scope") python/PythonStandardLibraryGroup -.-> python/math_random("Math and Random") subgraph Lab Skills python/variables_data_types -.-> lab-5002{{"Python 赋值表达式"}} python/numeric_types -.-> lab-5002{{"Python 赋值表达式"}} python/conditional_statements -.-> lab-5002{{"Python 赋值表达式"}} python/while_loops -.-> lab-5002{{"Python 赋值表达式"}} python/list_comprehensions -.-> lab-5002{{"Python 赋值表达式"}} python/function_definition -.-> lab-5002{{"Python 赋值表达式"}} python/scope -.-> lab-5002{{"Python 赋值表达式"}} python/math_random -.-> lab-5002{{"Python 赋值表达式"}} end

简单的赋值表达式

在这一步中,我们将从一个简单的示例开始,了解赋值表达式的基本语法。

打开 Python Shell

在终端中输入以下命令以打开 Python shell。

python3

简单测试

让我们从一个简单的示例开始:

## 赋值表达式的基本示例
n = 5
result = (squared := n * n)
print(squared, result)

输出:

25 25

在这里,我们使用海象运算符 := 在括号内将 n * n 的结果赋值给变量 squared。然后,我们将 squared 的值赋值给变量 result。最后,我们打印 squaredresult 的值。

在条件语句中使用赋值表达式

在这一步中,我们将探索如何在条件语句中使用赋值表达式。

## 在条件语句中使用赋值表达式
input_str = "Hello, world!"
if (length := len(input_str)) > 10:
    print(f"The string has {length} characters, which is more than 10.")
else:
    print(f"The string has {length} characters, which is less than or equal to 10.")

输出:

The string has 13 characters, which is more than 10.

在这里,我们使用海象运算符在 if 语句的条件中计算 input_str 的长度并将其赋值给变量 length。这使得我们可以在条件语句的两个分支中使用 length 的值。

在循环中使用赋值表达式

现在,让我们看看如何在循环中使用赋值表达式。

## 在循环中使用赋值表达式
numbers = [1, 2, 3, 4, 5]
while (n := numbers.pop()) > 2:
    print(f"Popped {n}, which is greater than 2.")
print(f"Popped {n}, which is less than or equal to 2.")

输出:

Popped 5, which is greater than 2.
Popped 4, which is greater than 2.
Popped 3, which is greater than 2.
Popped 2, which is less than or equal to 2

在这个示例中,我们在 while 循环的条件中使用海象运算符从 numbers 列表中弹出元素并将其赋值给变量 n。循环会持续进行,直到弹出的元素小于或等于 2。

在列表推导式中使用赋值表达式

最后,让我们探索如何在列表推导式中使用赋值表达式。

## 在列表推导式中使用赋值表达式
from math import sqrt

numbers = [1, 4, 9, 16, 25]
roots = [int(root) for n in numbers if (root := sqrt(n)) == int(root)]
print(roots)

输出:

[1, 2, 3, 4, 5]

在这个示例中,我们在列表推导式中使用海象运算符来计算 numbers 中每个数字的平方根,并检查它是否为整数。如果是整数,我们将该整数平方根添加到 roots 列表中。

总结

在本实验中,我们通过一系列逐步的示例探索了 Python 的赋值表达式(海象运算符)。我们涵盖了在条件语句、循环和列表推导式中的基本语法和用法。现在,你应该对如何在 Python 代码中使用赋值表达式来优化和简化复杂表达式有了很好的理解。

请记住,明智地使用赋值表达式可以使你的代码更具可读性和效率。与任何编程功能一样,重要的是不要过度使用它,因为如果使用过多或不恰当,可能会导致代码难以维护。

继续在不同的场景中练习和尝试使用海象运算符,以提高你的 Python 编程技能。祝你好运,编程愉快!