Lambda expressions in Python

Source: Internet
Author: User

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)


 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.