lambda expression in Python

Source: Internet
Author: User

First, lambda function 1, the basis of the lambda function: The lambda function is also called an anonymous function, that is, the function does not have a specific name, and the method created with Def is a name. as follows: [Python] View plain copy "" "named Foo function" "Def foo (): Return ' Beginman ' #Python中单行参数可以和标题写在一行" "" Lambda keyword creates an anonymous function that is the same as the above The function "" "Lambda: ' Beginman ' above simply creates a function object with lambda, does not save it and does not call it, and it is always recycled. Here we save and invoke: [Python] view plain Copybar = lambda: ' Beginman ' Print bar () #beginman from the above examples, it is easy to understand Python lambda syntax: [pytho N] View plain COPYLAMBDA [arg1[,arg2,arg3....argn]]:expression Lambda statement, the colon is preceded by a parameter, can have multiple, separated by commas, the return value to the right of the colon. A lambda statement is actually built as a function object. [Python] View plain copyprint lambda: ' Beginman ' #<function <lambda> at 0x00b00a30> 2, no parameters If there are no parameters, the lambda colon precedes No, as in the above example. 3. Parameters [Python] View plain copydef Add (x, y): return x+y add2 = lambda x,y:x+y print add2 (#3 def sum (x,y=10): RET Urn X+y sum2 = lambda x,y=10:x+y print sum2 (1) #11 print sum2 (1,100) #101 second, the Lambda and def examples above, the lambda function simply creates a simple The function object, which is a single-line version of a function, is called when it bypasses the stack allocation of the function for performance reasons. What else does Python lambda have to do with Def? The difference between def and Lambda: The main difference is that Python def is a statement and Python LamBDA is an expression, and understanding it is important for you to understand them.  There are a few caveats to using the lambda function: The lambda function can receive any number of arguments (including optional parameters) and return the value of a single expression. A lambda function cannot contain commands and cannot contain more than one expression. 1. Python lambda creates a function object, but does not assign the function object to an identifier, and Def assigns the function object to a variable. [Python] View plain copy>>> def foo (): Return ' foo () ' >>> foo <function foo at 0x011a34f0> 2, PYT Hon Lambda It's just an expression, and DEF is a statement. A lambda expression runs like a function when it is called to create a Frame object. Third, the use of lambda functions the following: 1. For single-line functions, using lambda eliminates the process of defining a function, making the code more streamlined. 2. In the case of a function that is not called more than once, the lambda expression is used in both the acquired and performance-enhancing considerations: In.. If can do, it is best not to choose lambda Four, reference http://www.cnblogs.com/coderzh/archive/2010/04/30/python-cookbook-lambda.htmlhttp:// The WWW.CNBLOGS.COM/WANPYTHON/ARCHIVE/2010/11/01/1865919.HTMLLAMBDA expression is a function of sketching. Allows the definition of a function to be embedded within the code. [Python] View plain copylist (filter (lambda x:true if x% 3 = = 0 Else False, Range (100))) as shown above, a lambda expression is used to define an anonymous function for filtering 10 A multiple of 3 within 0, and a list is generated. [Python] View plain copydef make_repeat (n): return lambda s:s * N Of course lambda can also be nested within a function, as above, a lambda expression nested inside a function. [Python] View plain copydouble = make_repeat (2) Double <function make_repeat.<locals>.<lambda> at 0x0000000003a01d90> Then, you can use a variable to receive, display double variable, double variable is a function, And you need a parameter, see lambda expression, which requires an S-parameter. [Python] View plain copyprint (double (8)) 16 Finally, call the double variable and pass in parameter 8 to get the return value 16. Because the previous value of N passed in is 2, 2 * 8 gets 16. Built-in BIF Introduction: Filter (): Simple to understand as a filter, requires two parameters, function, and a sequence (string, list, tuple is a sequence), the filter will sequentially pass the value of the sequence into the function, if it returns true, it will regenerate a list returned.  [Python] View plain copylist (filter (lambda x:true if x% 3 = = 0 Else False, Range (100))) [0, 3, 6, 9, 12, 15, 18, 21, 24, (+), (+),---------------------------------       Copyvalues = [' 1 ', ' 2 ', '-3 ', '-', ' 4 ', ' N/A ', ' 5 '] def is_int (val): try:x = Int (val) return True Except Valueerror:return False ivals = List (filter (Is_int, values)) the print (ivals) filter () function creates an iterator, so If you want a list, you have to make it like an example. Use list () to convert.    Zip (): the literal meaning of understanding, that is, zip packaging, you can package multiple sequences, it will split the sequence, and then the first sequence and the second sequence of elements to form a tuple, 2 groups of groups to synthesize the list. Note, however, that this is combined in the shortest sequence, meaning that if a sequence is longer, a comparisonShort, the combination will only go to the last element of the broken sequence, and the extra part will be discarded. [Python] View plain copy>>> str1 = "ABCDE" >>> str2 = "ABCDEFG" >>> list (Zip (str1, str2)) [( ' A ', ' a '), (' B ', ' B '), (' C ', ' C '), (' d ', ' d '), (' E ', ' e ')] map (): Map, usage and filter () are similar, but also the sequence is put into a function to operate, but regardless of the result of the operation, map , which is the main difference between map () and filter (). Note that the function in filter () and map () must have a return value. [Python] View plain copy>>> list (map (lambda x:true if x% 3 = = 0 Else False, range)) [True, False, False, T Rue, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, Tru  E, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, False, true, False, False, True, False, False, True, False, False, True, False, False, True, False, False, True, False, F Alse, False, True, False, False, True, False, False, True, False, False, True, False, False, True, Fal SE, False, True, False, False, True, False, False, TruE, False, False, True, False, False, True, False, False, True, False, False, True, False, False, true] I agree with the view of life in the movie "Godfather": The first step to achieve self-worth, the second step to take full care of the family, the third step to help the good people as far as possible, the fourth step for the ethnic voice, the fifth step for the national honor. In fact, as a man, the first two steps to success, life has been a complete, to achieve the third step is great, and the arbitrary reversal of the order of those who are generally not trustworthy.    [Plain] View plain COPYF = Lambda x,y,z:x+y+z print f (all in a) G = lambda x,y=2,z=3:x+y+z print g (1,z=4,y=5) #lambda表达式常用来编写跳转表 (jump table) is the list or dictionary of behaviors. For example: L = [(Lambda x:x**2), (Lambda x:x**3), (lambda x:x**4)] Print l[0] (2), L[1] (2), l[2] (2) D = {' F1 ':(lambda:2+3), ' F2 ':(lambda:2*3), ' F3 ':(lambda:2**3 '} print d[' F1 '] (), d[' F2 '] (), d[' F3 '] () #3, L  AMBDA expressions can be nested, but from a readability standpoint, you should try to avoid using nested lambda expressions. #4, the map function can manipulate the mapping function in the sequence. Example: DEF Inc (X): return x+10 L = [1,2,3,4] Print map (inc,l) print map ((lambda x:x+10), L) # 5, list parsing can implement the same function as the map function, and is often faster than map. For example: print [x**2 for x in range] Print map ((lambda x:x**2), Range ()) #6, list parsing is more powerful than map. For example: print [x+y for x in range (5) if x%2 = = 0 for y in range (x) if y%2 ==1] #7, generator functions are like general functions, but they are used as implementations of iterative protocols, so generator functions can only appear in an iterative context. For example: Def gensquares (n): For I in range (n): Yield i**2 for I in Gensquares (5): Print I, #8,  Some iterations (including for loops, map calls, list parsing, and so on) will automatically call the ITER function to see if the iteration protocol is supported. #9, generator expressions are like List parsing, but they are expanded in parentheses () rather than in square brackets []. For example: For num in (x**2 for X in range (5)): Print num, #10, list resolution has better performance than for loop.  However, performance should not be a top priority when writing Python code.  #11, when there is no return statement, the function returns the None object. #12, the concept of function design: #耦合性: Use a global variable only if it is really necessary #耦合性: Do not change parameters of a mutable type unless the caller wishes to do so #耦合性: Avoid directly altering variables in another file module [plain] View plain copy# aggregation: Each function should have a single, unified target #13, and finally give an example of a default parameter and a mutable parameter: Def saver (x=[]): X.append (1) Print x saver ([2]) saver () Saver () Saver ()

  

lambda expression in Python

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.