Lambda expressions are frequently used in Python, which summarizes the common methods of lambda expressions.
First, understand that lambda expression exists in Python as a constructor for an anonymous function. Second, it is important to understand that the common scenario for lambda expressions is that the use of lambda expression correspondence functions is very limited (therefore, there is no need to specifically define a non-anonymous function), while guaranteeing the simplicity of the code.
The simplest example of a lambda expression and the corresponding non-anonymous function:
F = lambda x:x + 1print (f (1))
def h (x): return x + 1print (H (1))
A lambda expression with one parameter and the corresponding non-anonymous function:
def f (n): Return lambda x:x/Nprint (f (1) (2)) # n=1; x=2
def g (n): Return lambda x:x/nk = g (1) # N=1print ((K (2)) # x=2
def h (x,n): Return X/nprint (H (2,1)) #x = 2; N=1
Lambda anonymous functions are often used in the filter (), map (), reduce (), sorted () functions, where the common denominator of these functions is that they all require function-type arguments, and lambda expressions apply exactly. Taking the sorted function as an example, its key parameter specifies a function that is responsible for extracting the comparison key from the sorted list.
club_ranking = [ (' Arsenal ', 3), (' Chelsea ', 1), (' Manchester city ', 2), (' Manchester ', 4),]club_ sorted = sorted (club_ranking, key = Lambda x:x[1]) # Sort by Rankingprint (club_sorted)
"In Python3.4 need to use Functools to convert the CMP function to the key function ' Import functoolsclub_ranking = [ (' Arsenal ', 3), (' Chelsea ', 1) , (' Manchester city ', 2), (' Manchester ', 4),]def get_ranking (x, y): #define CMP Functionreturn x[1]-Y[1]club _sorted = sorted (club_ranking, key = Functools.cmp_to_key (get_ranking)) # Sort by Rankingprint (club_sorted)
A small analysis of lambda expressions in Python