Functional programming and built-in functions-anonymous functions

Defined with lambda

lambda parameter: expression (what to do)

lambda x: x + 1                #x is a defined parameter, followed by a colon, how to deal with this parameter, the value obtained by default return 
func = lambda x: x + 1 #Need to assign this anonymous function to another A function name 
print (func (99)) 
# The output result is 100

name="alxe"
lambda x:x+"_sb"
func=lambda x:x+"_sb"
print(func("name")) #运行结果alxe_sb

  

The role of anonymous functions:

Lambda is usually used in combination with other function names

The calculation method of the function can also be written in the form of judgment, as follows

lambda x: x.startswith ( "n" ) # determines whether the string begins with n- 
FUNC the lambda = X: x.startswith ( "n-") 
Print (FUNC ( "asdasd")) 
# output is false

 Of course, anonymous functions can also input multiple variables and return multiple values. The default is in the form of a tuple (add a parenthesis when defining it to form a tuple). The example is as follows

lambda x, y, z: (x + 1, y + 1, z + 1)
 func = lambda x, y, z: (x + 1, y + 1, z + 1) #Note, one must be added later Parentheses 
a = func (1123,345,767) 
print (a) #The output result is (1124, 346, 768)

  

Guess you like

Origin www.cnblogs.com/yxzymz/p/12737314.html