How does a lambda expression capture external variables?

WBOY
Release: 2024-04-25 17:24:01
Original
433 people have browsed it

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.

lambda 表达式如何捕获外部变量?

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 参数列表: 表达式
Copy after login

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
Copy after login

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]
Copy after login

In this example, the lambda expression captures thexvariable in the outer scope and calculatesx# 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!