python —匿名函数(lambda)

匿名函数

一、定义

用lambda关键词能创建小型匿名函数,这种函数能得名与省略了用def声明函数的标准步骤。

lambda函数语法只包含一个句型,如下

lambda[arg1[arg2,arg3.........argn]]:expression      简洁,后只能接表达式 不能接复杂语法

def声明函数与匿名函数
>>> def  test(a,b):
    return a+b

>>> test(1,23)
24
>>> func = lambda x,y:x+y
>>> func(1,23)
24
>>> 

二、使用:

作为普通函数的补充

1.动态编程中:取决于func的要求(python是动态语言)

>>> def   test1(a,b,func):
    result = func(a,b)
    return result>>> test1(21,3,lambda x,y:x*y)
>>> 63

1,test1中21传入a ,3传入b, lambda x ,y:x*y 传给了func

2,把  a传给了x,把 b 传给了y

3,表达式执行结果返回给result

 

 2.匿名函数在列表排序中的使用(匿名函数功能:返回列表中每个元素(字典)的“name”或者“age”对应的值进行比较排序)

 1 >>> list1=[{"name":"zs","age":15},{"name":"li","age":25},{"name":"wu","age":19}]
 2 >>> list1.sort()
 3 Traceback (most recent call last):
 4   File "<pyshell#1>", line 1, in <module>
 5     list1.sort()
 6 TypeError: '<' not supported between instances of 'dict' and 'dict'
 7 >>> list1.sort(key = lambda x:x['name'])
 8 >>> list1
 9 [{'name': 'li', 'age': 25}, {'name': 'wu', 'age': 19}, {'name': 'zs', 'age': 15}]
10 >>> list1.sort(key = lambda x:x['age'])
11 >>> list1
12 [{'name': 'zs', 'age': 15}, {'name': 'wu', 'age': 19}, {'name': 'li', 'age': 25}]
13 
14 >>> help(list.sort)
15 Help on method_descriptor:
16 
17 sort(self, /, *, key=None, reverse=False)
18     Stable sort *IN PLACE*.
19 
20 >>> #这里的key指的是sort函数内部的key,不传入值时,默认为列表内元素,即此时字典传入x中,再运算结果,为对应年龄或者名称首字母排序

posted @ 2020-01-07 22:02  yescarf  阅读(254)  评论(0编辑  收藏  举报