Usage of lambda expressions in python

Source: Internet
Author: User
Tags python list
This article mainly introduces the usage of lambda expressions in python, and analyzes in detail the functions, definitions, usage methods, and related skills of lambda functions, for more information about lambda expressions in python, see the following example. We will share this with you for your reference. The details are as follows:

Here we will introduce lambda functions.

Lambda functions are the smallest function that quickly defines a single row. they are borrowed from Lisp and can be used wherever functions are needed. The following example compares the traditional function definition def with the lambda definition method:

>>> def f ( x ,y):...   return x * y...>>> f ( 2,3 )6>>> g = lambda x ,y: x * y>>> g ( 2,3 )6

As you can see, the results of the two functions are the same. for functions that implement simple functions, using lambda functions for definition is more streamlined and flexible. you can also assign a function to a variable directly, the variable name is used to represent the function name.

In fact, lambda functions do not need to assign values to a variable in many cases.

Note: lambda functions can receive any number of parameters (including optional parameters) and return the values of a single expression. Lambda functions cannot contain commands and cannot contain more than one expression.

The following describes how to use the lambda function to implement custom sorting.

class People :  age = 0  gender = 'male'  def __init__ ( self , age , gender ):    self . age = age    self . gender = gender  def toString ( self ):    return 'Age:' + str ( self . age ) + ' /t Gender:' + self . genderList = [ People ( 21 , 'male' ), People ( 20 , 'famale' ), People ( 34 , 'male' ), People ( 19 , 'famale' )]print 'Befor sort:'for p in List :  print p . toString ()List . sort ( lambda p1 , p2 : cmp ( p1 . age , p2 . age ))print ' /n After ascending sort:'for p in List :  print p . toString ()List . sort ( lambda p1 , p2 : - cmp ( p1 . age , p2 . age ))print ' /n After descending sort:'for p in List :  print p . toString ()

The code above defines a People class and uses the lambda function to sort the list of People objects in ascending and descending order according to the age of People. The running result is as follows:

Befor sort:
Age: 21 Gender: male
Age: 20 Gender: famale
Age: 34 Gender: male
Age: 19 Gender: famale
After ascending sort:
Age: 19 Gender: famale
Age: 20 Gender: famale
Age: 21 Gender: male
Age: 34 Gender: male
After descending sort:
Age: 34 Gender: male
Age: 21 Gender: male
Age: 20 Gender: famale
Age: 19 Gender: famale

Lambda statements are used to create new function objects and return them at runtime.

Example: Use lambda

#!/usr/bin/python# Filename: lambda.pydefmake_repeater(n):  return lambda s: s*ntwice = make_repeater(2)print twice('word')print twice(5)

Output:

$ python lambda.pywordword10

How it works

Here, we use the make_repeater function to create a new function object at runtime and return it.

Lambda statements are used to create function objects. Essentially, lambda requires a parameter, followed by a single expression as the function body, and the value of the expression is returned by the newly created function. Note that even print statements cannot be used in the lambda format, but expressions are only allowed.

Difference between def and lambda

The main difference between them is that python def is a statement and python lambda is an expression. understanding this is very important for you to understand them. Let's take a look at their applications.
First, the statements in python can be nested. for example, if you need to define a method based on a certain condition, you can only use def.

If you use lambda, an error is reported.

a = 2if a > 1 :  def info ():    print 'haha'else :  def test ():    print 'test'

Sometimes, when you need to operate in a python expression, you need to use expression nesting. in this case, python def cannot get the desired result, so you can only use python lambda.

The following is an example:

g = lambda x : x+2info = [g(x) for x in range(10)]print info

Through the above example, we hope you can understand the similarities and differences between python def and lambda. If you are interested in python functions, you can see: python function return values, python function parameters

Python lambda uses lambda in python to create anonymous functions, while the method created with def has a name, except that the method names on the surface are different, what are the differences between python lambda and def?

① Python lambda creates a function object, but does not assign this function object to an identifier, while def assigns the function object to a variable.

② Python lambda is just an expression, while def is a statement.

The following is a simplified python lambda format.

lambda x: print x

If you use python lambda in python list parsing, it doesn't make much sense, because python lambda creates a function object, but it is discarded immediately, because you didn't use its return value, that is, the function object. Lambda is just an expression that can be directly used as a member of the python list or python dictionary, for example:

info = [lamba a: a**3, lambda b: b**3]

There is no way to directly replace it with the def statement. Because def is a statement, not an expression that cannot be nested in it, lambda expressions can only have one expression after. That is to say, in def, return can be returned or placed behind lambda. return cannot be used or defined behind python lambda. Therefore, statements such as if, for, or print cannot be used in lambda. lambda is generally only used to define simple functions.

Here are some examples of python lambda.

① For a single parameter:

g = lambda x:x*2print g(3)

The result is 6.

② For multiple parameters:

m = lambda x,y,z: (x-y)*zprint m(3,1,2)

Result 4

It's okay to use python lambda to write programs ..

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.