Python 匿名函数

匿名函数定义:

lambda  参数:式子

eg :

func = lambda x, y:x+y  #x, y 相当于是形参

调用:

func(10, 20)  #此时 10 给 x , 20给y

如果普通函数没有return 将返回None ,匿名函数自带return 如上函数默认返回x + y

 

匿名函数字典排序:

stus s是一个字典,那么是一个key

stus.sort(key = lambda x:x['name']

 按名字排序从小到大

 

匿名函数用法:

def test(a ,b, func):
  result =func(a, b)

  print(result)

test (11, 22, lambda x, y:x+y)  #传入匿名函数当参数,当把x+y 换位 x-y test 就是算两个数的减法

 

匿名函数高级用法:

eg:

def test(a ,b, func):
    result =func(a, b)
    print(result)
func_new = input("请输入一个匿名函数:")
func_new = eval(func_new)  #eval的作用是 把input传入的字符串去点引号
test (11, 22, func_new) 

 

posted on 2020-03-25 14:06  pooopun  阅读(128)  评论(0编辑  收藏  举报

导航