18、lambda 表达式
2022/7/1 23:25:57
本文主要是介绍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)
参考资料
http://www.imooc.com/wiki/pythonlesson1/pythonlambda.html
这篇关于18、lambda 表达式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现
- 2024-05-30我们小公司,哪像华为一样,用得上IPD(集成产品开发)?
- 2024-05-30java excel上传--poi
- 2024-05-30安装笔记本应用商店的pycharm,再安排pandas等模块,说是没有打包工具?
- 2024-05-29java11新特性