Home >Backend Development >Python Tutorial >Detailed explanation of lambda expression usage in python

Detailed explanation of lambda expression usage in python

WBOY
WBOYOriginal
2016-07-06 13:29:551663browse

The examples in this article describe the usage of lambda expressions in python. Share it with everyone for your reference, the details are as follows:

Here I will introduce to you the lambda function.

The lambda function is a minimal function that quickly defines a single line. It is borrowed from Lisp and can be used wherever a function is needed. The following example compares the traditional function definition def and lambda definition methods:

>>> 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 obtained by the two functions are the same. For functions that implement simple functions, it is more streamlined and flexible to use lambda functions to define them. You can also directly assign the function to a variable and use the variable name to represent the function. name.

In fact, lambda functions do not need to be assigned to a variable in many cases.

There are some things to note when using lambda functions: The lambda function can receive any number of parameters (including optional parameters) and return the value of a single expression. The lambda function cannot contain commands and cannot contain more than one expression .

The following is a brief demonstration of 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 . gender
List = [ 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 above code defines a People class, and uses the lambda function to sort the list containing People class objects in ascending and descending order according to People's age. The running results are 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: Using lambda form

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

Output:

$ python lambda.py
wordword
10

How it works

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

The lambda statement is used to create function objects. Essentially, a lambda takes 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 lambda form, only expressions can be used.

The 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 important for you to understand them. Take a look at their applications below.
First of all, statements can be nested in python. For example, if you need to define a method based on a certain condition, you can only use def.

You will get an error if you use lambda.

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

Sometimes when you need to operate in python expressions, you need to use expression nesting. In this case, python def cannot get the results you want, so you can only use python lambda

Here’s an example:

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

Through the above examples, I hope you can have a good understanding of the similarities and differences between python def and lambda. If you are interested in python functions, you can take a look: python function return value, python function parameters

Python lambda uses lambda in python to create anonymous functions, and methods created with def have names. In addition to the superficial method names being different, what else is different about python lambda from def?

① python lambda will create a function object, but will not assign the function object to an identifier, while def will assign the function object to a variable.

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

The following is the format of python lambda, it looks so streamlined.

lambda x: print x

If you use python lambda in python list analysis, I feel that it is not very meaningful, because python lambda will create a function object, but then discard it immediately because you do not use its return value, that is, function object. It is precisely because lambda is just an expression, it can be directly used as a member of a python list or a python dictionary, such as:

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

There is no way to directly replace it with a def statement in this place. Because def is a statement, not an expression, which cannot be nested inside. A lambda expression can only have one expression after ":". That is to say, in def, things that can be returned with return can also be placed after lambda, and things that cannot be returned with return cannot be defined after python lambda. Therefore, statements like if or for or print cannot be used in lambdas. Lambdas are generally only used to define simple functions.

Here are some examples of python lambda

① Single parameter:

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

The result is 6

② Multiple parameters:

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

The result is 4

When you have nothing to do when writing programs, you can become proficient by using python lambda. .

Readers who are interested in more Python-related content can check out the special topics on this site: "Summary of Python Image Operation Skills", "Python Data Structure and Algorithm Tutorial", "Python Socket Programming Skills Summary", "Python Function Using Skills Summary" ", "Python String Operation Skills Summary", "Python Introduction and Advanced Classic Tutorial" and "Python File and Directory Operation Skills Summary"

I hope this article will be helpful to everyone in Python programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn