The lambda expression captures the external variable by creating a reference to the variable in the external scope. The specific steps include: The lambda expression captures the external variable when it uses it. Lambda expressions can only capture local variables in external functions, not global variables. If the external variable is reassigned, the reference captured in the lambda expression is also updated.
How lambda expression captures external variables
lambda expression is an anonymous function and can access the enclosing scope (enclosing scope) variables in . When a lambda expression captures an external variable, it creates a reference to that variable.
Syntax
lambda 参数列表: 表达式
Capture external variables
If the lambda expression uses variables declared in the external scope, then This variable will be captured.
# 定义外部函数 def outer_function(): outer_variable = 10 # 定义 lambda 表达式,捕获 outer_variable my_lambda = lambda: outer_variable # 调用 lambda 表达式,获取外部变量 result = my_lambda() print(result) # 输出: 10
Notes
lambda expressions can only capture local variables in external functions, not global variables. Additionally, if the external variable is reassigned, the reference captured in the lambda expression is also updated.
Practical case
# 使用 lambda 表达式对列表中的数字进行排序 numbers = [4, 2, 8, 1, 6] # 根据数字的平方对列表进行排序 sorted_numbers = sorted(numbers, key=lambda x: x**2) # 打印排序后的列表 print(sorted_numbers) # 输出: [1, 4, 2, 6, 8]
In this example, the lambda expression captures the x
variable in the outer scope and calculates x# The square of ## is used as the sorting basis.
The above is the detailed content of How does a lambda expression capture external variables?. For more information, please follow other related articles on the PHP Chinese website!