python学习笔记(21)——匿名函数

来源:互联网 发布:网络电视用什么播放器 编辑:程序博客网 时间:2024/06/06 15:39

匿名函数


1,lambda表达式:


语法:lambda x:f(x)

解释:三个部分分别是:关键字,参数,返回值

例子:lambda x:x+1  函数的意思:该函数返回x+1



2,过滤器filter


语法:

   filter(function or None, iterable) --> filter object
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.


解释:

1,filter有两个参数,第一个参数可以是一个函数或者是“None”,第二个参数是一个迭代器(可能是一个列表或者数组等)。

2,将迭代器里的每一个元素作为函数的参数计算(若第一个参数是None,则直接筛选迭代器里为true的值)。

,filter将进行计算,返回每次迭代器里计算结果为true的元素。


例子1(第一个参数为None):


数一开始返回的是一个可迭代对象,用列表显示该对象则将迭代器中的1,True筛选出来



例子2(第一个参数为函数):


该例子是筛选0到9里面的奇数


结合上面的lambda的表达式可以将其精简为下面一行代码



3,map函数


语法:map(temp1,temp2)

 map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.


解释:

1,map函数可有两个参数,第一个参数通常为函数

2,将第二个参数的里的元素作为参数传递给第一个参数的函数进行计算并返回运算结果


例子(将0到4分别加1):