Pythont特殊语法filter,map,reduce,apply使用方法
(1)lambda
lambda是Python中一个很有用的语法,它允许你快速定义单行最小函数。类似于C语言中的宏,可以用在任何需要函数的地方。
基本语法如下:
函数名=lambdaargs1,args2,...,argsn:expression
例如:
add=lambdax,y:x+y printadd(1,2)
(2)filter
filter函数相当于一个过滤器,函数原型为:filter(function,sequence),表示对sequence序列中的每一个元素依次执行function,这里function是一个bool函数,举例说明:
sequence=[1,2,3,4,5,6,7,8,9,10] fun=lambdax:x%2==0 seq=filter(fun,sequence) printseq
以下代码就是表示筛选出sequence中的所有偶数。
filter函数原型大致如下:
deffilter(fun,seq): filter_seq=[] foriteminseq: iffun(item): filter_seq.append(item) returnfilter_seq
(3)map
map的基本形式为:map(function,sequence),是将function这个函数作用于sequence序列,然后返回一个最终结果序列。比如:
seq=[1,2,3,4,5,6] fun=lambdax:x<<2 printmap(fun,seq)
map的函数源代码大致如下:
defmap(fun,seq): mapped_seq=[] foriteminseq: mapped_seq.append(fun(item)) returnmapped_seq
(4)reduce
reduce函数的形式为:reduce(function,sequence,initVal),function表示一个二元函数,sequence表示要处理的序列,而initVal表示处理的初始值。比如:
seq=[1,2,3,4,5,6,7,8,9,10] fun=lambdax,y:x+y printreduce(fun,seq,0)
表示从初始值0开始对序列seq中的每一个元素累加,所以得到结果是55
reduce函数的源代码大致如下:
defreduce(fun,seq,initVal=None): Lseq=list(seq) ifinitValisNone: res=Lseq.pop(0) else: res=initVal foriteminLseq: res=fun(seq,item) returnres
(5)apply
apply是用来间接地代替某个函数,比如:
defsay(a,b): printa,b apply(say,(234,'HelloWorld!'))