004-lambda.py

语法

lambda_expr ::= lambda [parameter_list]: expression

官方文档介绍:

Lambda expressions (sometimes called lambda forms) are used to create anonymous functions.

简单说:
1. 匿名函数
2. 只有一句代码
3. 通常在需要函数作为参数的情况下使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# lambda_expr_nocond example
lambda_expr_nocond = lambda x: x * 2
print(lambda_expr_nocond(5)) # Output: 10
print(lambda_expr_nocond(3)) # Output: 6

# 多个参数
x = lambda a, b, c: a + b + c
print(x(5, 6, 2)) # Output: 13

# 将函数与内置函数一起使用
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda num: num ** 2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 输出:[2, 4, 6, 8]

应用场景:

比如在PyQt 在信号传值的时候,可以使用lambda 匿名函数进行传递

参考个人工程

在项目中

1
2
3
4
5
6
7
8
9
10
def check_uop(self, sn):
### ... code omited ...
uop_thread.finished.connect(lambda response_text: check_uop_finish(self, response_text))
uop_thread.start()
### ... code omited ...


def check_uop_finish(self, res):
status = False
### ... code omited ...

上述代码中connect(...)需要函数名称作为参数,但是需要调用的函数需要参数;此时可以使用lambda匿名一个新函数来完成参数传递


004-lambda.py
https://jackiedai.github.io/2025/03/11/011Python/005Python-lambda/
Author
lingXiao
Posted on
March 11, 2025
Licensed under