anonymous function lambda
Defining anonymous functions
Lambda
def fun (x, y):
Return X*y
R=lambda X,y:x*y
R (3,4)
In [2]: R = lambda x, y:x *yin [3]: R (3,4) out[3]: 12
Lambda Basics
In a lambda statement, the colon is preceded by a parameter, can have multiple, separated by commas, and the right side of the colon is the return value
The lambda statement constructs an object that is actually a function
Advantages of Lambda anonymous functions:
1, using Python to write a script, using lambda can save the process of defining functions, so that the code is more streamlined
2, for some abstract, will not be another place to re-use the function, sometimes the function of a name is also a problem, using lambda does not need to consider the problem of naming
3. Use lambda to make your code easier to understand at some point
Usage of reduce:
is to deal with the sequence sequence by function (), the function () within the reduce must be a two-yuan calculation, two subtraction
Reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) Calculates processing: ((((((1+2) +3) +4) +5)
Help (reduce)
Reduce (...) reduce (function, sequence[, initial]) -> value apply a function of two arguments cumulatively to the items of a sequence, from Left to right, so as to reduce the sequence to a single value. for example, reduce (Lambda x, y: x+y, [1,  2, 3, 4, 5]) calculates ((((1+2) +3) +4) +5). if initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. (END) In [8]: def add (x, y): ...: return x+y ...: In [9]: Reduce (Add,range (1,101)) # 1+2+3+4+5+ ... 100=5050out[9]: 5050in [10]: reduce (Lambda x,y:x+y,range (1,101)) # 1+2+3+4+5+ ...... 100=5050out[10]: 5050in [11]: reduce (Lambda x,y:x*y,range (1,6)) # 5*4*3*2*1Out[ 11]: 120
This article comes from "Plum blossom fragrance from bitter cold!" "Blog, be sure to keep this provenance http://daixuan.blog.51cto.com/5426657/1846978
Python Learning note 10-anonymous function lambda