18、lambda 表达式
将函数作为第一类对象
什么是第一类对象
将对象赋值给变量
number = 123
string = "hello"
list = [1, 2, 3]
dict = {'name': 'tom', 'age': 12}
将对象作为参数传递
print(123)
print("hello")
print([1, 2, 3])
print({'name': 'tom', 'age': 12})
将对象用作返回值
def return_number():
return 123
def return_string():
return "hello"
def return_list():
return [1, 2, 3]
def return_dict():
return {'name': 'tom', 'age': 12}
将函数作为第一类对象
可以将函数赋值给变量
def max(a, b):
if a > b:
return a
else:
return b
var = max
print('max = %d' % var(1, 2))
可以将函数作为参数传递
def func():
print('Inside func')
def pass_func(data):
print('Inside pass_func')
data()
pass_func(func)
可以将函数作为返回值
def func():
print('Inside func')
def return_func():
print('Inside return_func')
return func
var = return_func()
var()
将函数作为第一类对象的意义
将函数作为第一类对象,是一种重要的抽象机制,极大的提升了程序的灵活性。通过一个例子进行说明。假设需要完成这样的任务:
- 存在一个列表 [1, -1, 2, -2, 3, -3]
- 打印输出列表中的正数
- 打印输出列表中的负数
我们使用两种方法实现:
- 包含重复性代码的解决方法
- 将函数作为参数传递
包含重复性代码的解决方法
list = [1, -1, 2, -2, 3, -3]
def print_positive(list):
for item in list:
if item > 0:
print(item)
def print_negative(list):
for item in list:
if item < 0:
print(item)
print_positive(list)
print_negative(list)
将函数作为参数传递
list = [1, -1, 2, -2, 3, -3]
def select_positive(x):
return x > 0
def select_negative(x):
return x < 0
def select(list, select_function):
for item in list:
if select_function(item):
print(item)
select(list, select_positive)
select(list, select_negative)
匿名函数 lambda
lambda 表达式的定义
在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。
lambda x: x > 0
该函数等价于函数 select_positive,如下所示:
def select_positive(x):
return x > 0
使用 lambda 表达式重写程序
在前面的小节中,将函数作为参数,编写程序实现打印正数和负数。下面使用 lambda 表达式重写这个程序:
list = [1, -1, 2, -2, 3, -3]
def select(list, select_function):
for item in list:
if select_function(item):
print(item)
select(list, lambda item: item > 0)
select(list, lambda item: item < 0)
map 函数
map 函数接收两个参数 function 和 list,function 是一个函数,list 是一个可以被遍历的序列,map 将传入的函数依次作用到序列的每个元素,并把结果作为新的序列返回。
list = [1, 2, 3]
list2 = map(lambda x: x * 2, list)
for item in list2:
print(item)
list10 = map(lambda x: x + 10, list)
for item in list10:
print(item)