python之lambda表达式

来源:互联网 发布:淘宝买iphone那个店 编辑:程序博客网 时间:2024/06/01 08:37

lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。

lambda表达式是起到一个函数速写的作用。允许在代码内嵌入一个函数的定义。

事例(创建匿名函数):
>>>g=lambda x:2*x+1//冒号前面是变量,冒号后面是表达式
>>>g(5)
11
>>>g=lambda x,y:x+y
>>>g(2,3)

5

我们首先看看内置函数:

******* filter()

看注释:help(filter)

>>> help(filter)
Help on built-in function filter in module __builtin__:


filter(...)
    filter(function or None, sequence) -> list, tuple, or string
    
    Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or string, return the same type, else return a list.


>>>list(filter(None,[1,0,False,True]))
[1,True]

同时,我们可以用自定义的函数odd:

>>>def odd(x):
return x%2
>>>temp = range(10)
>>>show = filter(odd,temp)
>>>list(show)
[1,3,5,7,9]


把它写成一个函数(filter的第一参数是function or None

>>>list(filter(lambda x:x%2,range(10)))
>>> list(filter(lambda x:x%2 ,range(5)))
[1, 3]
******映射map()
>>> list(map(lambda x:x%2 ,range(5)))

[0, 1, 0, 1, 0]

这里定义了一个action函数,返回了一个lambda表达式。其中lambda表达式获取到了上层def作用域的变量名x的值。

a是action函数的返回值,a(22),即是调用了action返回的lambda表达式。

>>> def action(x):
return lambda y:x+y

>>> a = action(2)
>>> a(10)
12

这里也可以把def直接写成lambda形式。如下:

>>> b = lambda x:lambda y:x+y
>>> a = b(3)
>>> a(2)
5


原创粉丝点击