博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 匿名函数
阅读量:7239 次
发布时间:2019-06-29

本文共 1033 字,大约阅读时间需要 3 分钟。

匿名函数

  • 函数可以像普通变量一样进行赋值

    def hello():     print('hello world') ​ print(hello.__name__) a = hello print(a.__name__) hello() a()
  • 函数可以作为参数传递,扩展函数的功能

    def add(a, b):     return a+b def calc(a, b, func): return func(a, b) print(calc(2, 3, add))
  • 场景:当函数作为另一个函数的参数,只使用一次也得定义,否则无法使用,于是匿名函数就出现了。

  • 定义:就是没有名字的函数,使用lambda关键字定义

  • 格式:

    • 以lambda开头

    • 后面跟上该匿名函数的参数,多个参数使用逗号隔开

    • 最后一个参数的后面跟上冒号':'

    • 冒号的后面跟上一个表达式,这个表达式就是返回值,不需要使用return

  • 示例1:

    def calc(a, b, func):     return func(a, b) # mul = lambda x, y: x*y # print(calc(3, 5, mul)) print(calc(3, 5, lambda x,y:x*y))
  • 示例2:

    # l = [5, 3, 2, 8, 6, 1] ​ l = [     {'name':'xiaowang', 'age':15, 'height':150},    {'name':'xiaodu', 'age':14, 'height':145},    {'name':'xiaopang', 'age':12, 'height':140},    {'name':'banhua', 'age':13, 'height':155}, ] ​ # def d_key(d): #     return d['age'] # l.sort(key=d_key) # 当列表中的元素无法直接比较大小时,需要传递参数key # key是一个函数,接受元素作为参数,返回用于比较的项 l.sort(key=lambda x:x['height']) ​ for i in l:    print(i)
  • 练习:

    • 试着自己封装一个列表的sort函数,接受参数:排序对象、key、reverse

转载于:https://www.cnblogs.com/kiki5881/p/8523414.html

你可能感兴趣的文章
老板不在,你不得不做出越权的决定,咋办?(考试题系列)
查看>>
如何解决SQL Server 2008 R2中“阻止保存要求重新创建表的更改”的问题!
查看>>
cloudstack 4管理器安装备忘
查看>>
sentry日志管理系统安装以及使用教程
查看>>
python-pip : Depends: python-setuptools (>= 0.6c1) 问题
查看>>
iptables外网一端口通过NAT转发内网一服务器端口上
查看>>
新书推荐
查看>>
程序与生活:生活要持续更新
查看>>
网络安全系列之四十九 IIS6.0权限设置
查看>>
VSphere client 虚拟机克隆及网卡报错处理
查看>>
【第一期】如何打造属于自己的网站编辑器——CKEditor与UEditor之争
查看>>
linux下卷组管理
查看>>
17个Linux系统高频率常用命令行和shell小脚本
查看>>
VisualSvn Server介绍
查看>>
Nginx性能测试工具之http_load
查看>>
为httpd服务器上单一的网站做客户机地址限制和用户授权限制知识补充
查看>>
Windows Server 2008终端服务详解系列4:TS网关的部署
查看>>
路由器通过NVI解决内网访问内部服务器的外部映射地址测试
查看>>
系统架构师-基础到企业应用架构-分层[上篇]
查看>>
【斗医】【2】Web应用开发20天
查看>>