Python3 reduce the usage and lambda

reduce () function to a data set (iterable [, initializer] can be seen to comprise initialization data and initialization data ranked No. 1, i.e., a first set of elements) all data subjected to the following operations: prior to the collection of function elements 1,2 function operation, then the resulting function computation function and the third element, and so on, to obtain a final result. 
 
lambda expressions, usually need a function, but do not want to bother to name the next occasion a function of use, but also refers to anonymous functions. 
 
In version 3 prior python can not write from functools import reduce.
After python 3, reduce longer in the built-in function, you have to use it from functools import reduce.
 
Example:
from functools import reduce  
a=reduce(lambda x,y:x*y,[1,2,3],5)
print(a)
Operation is:
5*1=5 
5*2=10 
10*3=30
 
from functools import reduce
a=reduce(lambda x,y:x+y**2,[1,2,3],3)
print(a)
Operation is:
3+1*1=4  
4+2*2=8 
8+3*3=17
 
from functools import reduce
a=reduce(lambda x,y:x*2+y*3,[4,6],3)
print(a)
Operation is:
3*2+4*3=18
18*2+6*3=54
 
 
If used alone lambda, examples:
MAXIMUM = lambda x, y: (x> y) * x + (x <y) * y
MINIMUM = lambda x,y :  (x > y) * y + (x < y) * x
a = 10
b = 20
c = 30
print 'The largar one is %d' % MAXIMUM(a,b,c)
print 'The lower one is %d' % MINIMUM(a,b,c)

Guess you like

Origin www.cnblogs.com/ratels/p/12171109.html