Lambda expressions in Python
Lambda expressions are often used in Python. Here we summarize the common methods of Lambda expressions.
First, you must understand that Lambda expressions exist in Python as an anonymous function constructor. Secondly, we need to understand that the common scenarios of Lambda expressions are that Lambda expressions have a limited number of functions (therefore, there is no need to define a non-Anonymous function), while ensuring the simplicity of the Code.
The simplest Lambda expression example and the corresponding non-Anonymous function:
f = lambda x: x + 1print ( f(1) )
def h (x):return x + 1print ( h(1) )
Lambda expressions with a parameter and their corresponding non-Anonymous functions:
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 filter (), map (), reduce (), sorted () functions. All these functions need function parameters, lambda expressions apply exactly. Taking the sorted function as an example, its key parameter specifies a function to extract comparison key from the list with sorting.
club_ranking = [ ('Arsenal', 3), ('Chelsea', 1),('Manchester City', 2), ('Manchester United', 4),]club_sorted = sorted(club_ranking, key = lambda x: x[1]) # sort by rankingprint (club_sorted)
''' In Python3.4, you need to use functools to convert the cmp function to the key function ''' import functoolsclub_ranking = [('arsenal', 3), ('chelsea', 1 ), ('manchester city', 2), ('manchester united', 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)