Pythont special syntax filter, map, reduce, apply usage, pythontreduce
(1) lambda
Lambda is a useful syntax in Python. It allows you to quickly define the smallest single row function. It is similar to a macro in C language and can be used wherever a function is needed.
The basic syntax is as follows:
Function name = lambda args1, args2,..., argsn: expression
For example:
add = lambda x,y : x + yprint add(1,2)
(2) filter
The filter function is equivalent to a filter. Its prototype is filter (function, sequence), which indicates that the function is executed for each element in the sequence in sequence. Here the function is a bool function, for example:
sequence = [1,2,3,4,5,6,7,8,9,10]fun = lambda x : x % 2 == 0seq = filter(fun,sequence)print seq
The following code filters out all the even numbers in the sequence.
The filter function prototype is roughly as follows:
def filter(fun,seq): filter_seq = [] for item in seq: if fun(item): filter_seq.append(item) return filter_seq
(3) map
The basic form of map is map (function, sequence). It is to apply the function to the sequence and then return a final result sequence. For example:
seq = [1,2,3,4,5,6]fun = lambda x : x << 2print map(fun,seq)
The source code of the map function is roughly as follows:
def map(fun,seq): mapped_seq = [] for item in seq: mapped_seq.append(fun(item)) return mapped_seq
(4) reduce
Reduce functions are in the form of reduce (function, sequence, initVal). function indicates a binary function, sequence indicates the sequence to be processed, and initVal indicates the initial value to be processed. For example:
seq = [1,2,3,4,5,6,7,8,9,10]fun = lambda x,y: x + yprint reduce(fun,seq,0)
Indicates that each element in sequence seq is accumulated from the initial value 0, so the result is 55.
The source code of the reduce function is roughly as follows:
def reduce(fun,seq,initVal = None): Lseq = list(seq) if initVal is None: res = Lseq.pop(0) else: res = initVal for item in Lseq: res = fun(seq,item) return res
(5) apply
Apply is used to indirectly replace a function, for example:
def say(a,b): print a,bapply(say,(234,'Hello World!'))