Lambda is a useful syntax in Python that allows you to quickly define a single-line minimum function. Similar to a macro in C, it can be used wherever a function is needed.
The basic syntax is as follows:
函数名 = lambda args1,args2,...,argsn : expression
For example:
Add = Lambda x,y:x + y
Print (ADD)
filter
function is equivalent to a filter, the function prototype is: filter(function,sequence)
, for each element in the sequence sequence execution function, where function is a bool function, for example:
= [1,2,3,4,5,6,7,8,9,10=lambda%2==0=filter(fun,sequence)print(seq)
The following code indicates that all the even numbers in the sequence are filtered out.
The filter function prototype is roughly as follows:
deffilter(fun,seq): = [] forin seq: if fun(item): filter_seq.append(item) return
The basic form of map is: Map (function,sequence), which functions the function on the sequence sequence and returns a final result sequence. Like what:
= [1,2,3,4,5,6=lambda<<2printmap(fun,seq)
The map's function source code is roughly as follows:
defmap(fun,seq): = [] forin seq: mapped_seq.append(fun(item)) return(mapped_seq)
The reduce function is in the form of:
reduce(function,sequence,initVal)
function
Represents a two-tuple function that represents the sequence
sequence to be processed, and initVal
represents the initial value of the processing. Like what:
= [1,2,3,4,5,6,7,8,9,10=lambda+ yprint(reduce(fun,seq,0))
Indicates that each element in the sequence SEQ starts with an initial value of 0, so the resulting result is 55
reduce
The source code for the function is roughly as follows:
defreduce=None): =list(seq) ifisNone: = Lseq.pop(0) else: = initVal forin Lseq: = fun(seq,item) return res
apply
is used to indirectly replace a function, such as:
def say(a,b): print(a,b)apply(say,(234,‘Hello World!‘))
Lambda-filter-reduce-apply-map of Python built-in functions