Python's anonymous function lambda interpretation and usage

Source: Internet
Author: User

The syntax for a lambda function contains only one statement, as follows: Lambda arg1,arg2,..... argn:expression (mainly see the following example)
code example:

#-*-coding:utf-8-*-# __author__ = "www.iplaypy.com" # ordinary Python function def Func (a,b,c): return a+b+c print func (1,2,3) # return value 6 # lambda anonymous function f = lambda a,b,c:a+b+c print F (1,2,3#< Span style= "color: #008000;" > return result is 6                

# Look at the Python sample code above, f = the keyword lambda in lambda a,b,c:a+b+c represents an anonymous function,
Return returns a value, and the expression itself results in a return value.

(Here are some of the code I copied, it is through the code so that I have a more in-depth understanding of the anonymous function, so suggest that you take a serious look,)

No parameter anonymous function:
------
>>> t = lambda:true #分号前无任何参数
>>> T ()
True

Functions equivalent to the definition of def below
>>> def func (): Return True
>>> func ()
True

------

>>> s = "This Is\na\ttest" #建此字符串按照正常情形输出
>>> s
' This is\na\ttest '
>>> print S.split () #split函数默认分割: spaces, line breaks, TAB
[' This ', ' is ', ' a ', ' test ']
>>> ". Join (S.split ()) #用join函数转一个列表为字符串
' This is a test '

Equivalent to

>>> (lambda S: ". Join (S.split ())") ("This Is\na\ttest")




anonymous function with parameters

>>> Lambda x:x**3 #一个参数
>>> Lambda X,y,z:x+y+z #多个参数

>>> Lambda X,y=3:x*y #允许参数存在默认值



anonymous function calls

#直接赋值给一个变量, and then again like the general function call

------

>>> C = Lambda x,y,z:x*y*z
>>> C (2,3,4)
24

------

>>> C = Lambda x,y=2:x+y #使用了默认值
>>> c #不输的话, using the default value of 2
12

------

>>> a = Lambda *z:z #*z Returns a meta-ancestor
>>> A (' Testing1 ', ' Testing2 ')
(' Testing1 ', ' Testing2 ')

------

>>> C = Lambda **arg:arg #arg返回的是一个字典
>>> C ()
{}

#直接后面传递实参

------

>>> (Lambda x,y:x if x> y else y) (101,102)
102

------

>>> (Lambda x:x**2) (3)
9

#lambda返回的值, combined with map,filter,reduce

>>> filter (lambda x:x%3==0,[1,2,3,4,5,6])
[3, 6]

Equivalent to the following list derivation

>>> L = [x for x in [1,2,3,4,5,6] if x%3==0]
>>> L
[3, 6]


Nested use

#lambda嵌套到普通函数中, the lambda function itself is the value of return

------

>>> def increment (n):
... return Lambda x:x+n
...
>>> F=increment (4)
>>> F (2)
6

------

>>> def say ():
... title = ' Sir, '
... action= Lambda X:title + x
... return action
...
>>> act = Say ()
>>> Act (' smith! ')
' sir,smith! '



A large number of examples:

Example 01: String union with default value or x= (lambda ...) This format

>>> x = (lambda x= "Boo", y= "Too", z= "Zoo": x+y+z)
>>> x ("Foo")
' Footoozoo '



Example 02: Federated Use with lists

>>> L = [Lambda x:x**2,\
Lambda x:x**3,\
Lambda X:x**4]

>>> for F in L:
... print f (2)
...
4
8
16

It can also be called as follows

>>> Print L[0] (3)
9

Example 03: Working with Dictionaries

>>> key = ' B '
>>> dic = {' A ': lambda:2*2,\
... ' B ': lambda:2*4,\
... ' C ': lambda:2*8}
>>> Dic[key] ()
8

Example 04: Finding the Minimum value

>>> lower = lambda x,y:x if x<y else y
>>> lower (' AA ', ' AB ')
' AA '



Example 05: Combined with map and list

>>> Import Sys
>>> ShowAll = Lambda x:list (map (sys.stdout.write,x))
>>> showall ([' jerry\n ', ' sherry\n ', ' alice\n '])
Jerry
Sherry
Alice

>>> showall ([' Jerry ', ' Sherry ', ' Alice '])
Jerrysherryalice

Equivalent to the following

>>> ShowAll = lambda x: [Sys.stdout.write (line) for line in X]
>>> showall (' i\t ', ' love\t ', ' you! ')
I Love you! [None, none, none]



Example 06: Defining an inline callback function in Tkinter

Import Sys
From Tkinter import Button,mainloop


x = Button (text= ' Press me ',
Command= (Lambda:sys.stdout.write (' hello,world\n ')))
X.pack ()
X.mainloop ()



>>>

hello,world!

hello,world!



Example 07:LAMBDA and map are used together,

>>> out = Lambda *x:sys.stdout.write (". Join (Map (str,x)))
>>> out (' The ', ' is ', ' a ', ' book!\n ')
This is a book!



Example 08: Judging whether a string starts with a letter

>>> Print (Lambda x:x.startswith (' B ')) (' Bob ')
True

-----

>>> Names = [' Anne ', ' Amy ', ' Bob ', ' David ', ' Carrie ', ' Barbara ', ' Zach ']
>>> b_name= Filter (lambda x:x.startswith (' B '), Names)
>>> B_name
[' Bob ', ' Barbara ']



Example 09:LAMBDA and map are used together:

>>> squares = map (lambda x:x**2,range (5))
>>> Squares
[0, 1, 4, 9, 16]



Example 10. Lambda and Map,filter are used together:

>>> squares = map (lambda x:x**2,range (10))
>>> filters = filter (lambda x:x>5 and X<50,squares)
>>> Filters
[9, 16, 25, 36, 49]



Example 11. Lambda and sorted are used together

#按death名单里面, sorted by age

#匿名函数的值返回给key, come in sort of

>>> death = [(' James ', 32),
(' Alies ', 20),
(' Wendy ', 25)]

>>> sorted (Death,key=lambda age:age[1]) #按照第二个元素, index 1 sorted
[(' Alies ', '), (' Wendy ', +), (' James ', 32)]



Example 12. Using lambda and reduce together

>>> L = [1,2,3,4]
>>> sum = reduce (lambda x,y:x+y,l)
>>> sum
10



Example 13. Ask for a prime number between 2-50

#素数: Numbers that can only be divisible by 1 or by themselves

>>> nums = range (2,50)
>>> for I in Nums:
Nums = filter (lambda x:x==i or x% i,nums)
>>> Nums
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]



Example 14. The and of the two list elements

>>> a = [1,2,3,4]
>>> B = [5,6,7,8]
>>> map (Lambda X,y:x+y, A, b)
[6, 8, 10, 12]



Example 15. Find the length of each word in a string

>>> sentence = "Welcome to beijing!"
>>> words = Sentence.split ()

>>> lengths = Map (lambda x:len (x), words)
>>> Lengths
[7, 2, 8]

Write a line:

>>> Print map (lambda X:len (x), ' Welcome to beijing! '). Split ())


Some references play snake net: http://www.iplaypy.com/wenda/lambda.html

Section Reference csdn:http://blog.csdn.net/csdnstudent/article/details/40112803

Python's anonymous function lambda interpretation and usage

Related Article

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.