#lambda expression form: lambda arguments1, arguments2,...argumentsN:expression using arguments f= lambda x,y,z:x+y+z print (f( 2 , 3 , 4 )) #9 #default arguments are also Can be used in lambda parameters as in def x=( lambda a= 'fee' ,b= 'fie' ,c= 'foe' :a+b+c) print (x()) # feefiefoe def knights(): title='sir' action=(lambda x:title+' '+x) return action a=knights() print (a( 'name' )) #sir name #lambda acts as a function shorthand, allowing the definition of a function to be embedded in the code used. When a small piece of execution code is required to be written into the def statement, it cannot be written in the syntax. where #lambda expressions are most useful as a shorthand for def l=[ lambda x:x** 2 , lambda x:x** 3 , lambda x:x** 4 ] for f in l: print (f( 2 )) #4 8 16 key= 'got' result={ 'already' :( lambda : 2 + 2 ), 'got' :( lambda : 2*4),'one':(lambda :2**6)}[key]() print(result) #8 lower=(lambda x,y:x if x<y else y) print(lower('bb','aa')) #aa print(lower('aa','bb')) #aa import sys showall=lambda x:list(map(sys.stdout.write,x)) showall(['a','b','c']) #abc showall1=lambda x:[sys.stdout.write(i) for i in x] showall1([ 'a' , 'b' , 'c' ]) #abc #Nested lambda expressions and scopes #lambda expressions can get variable names in any upper lambda def action(x): return ( lambda y : x+y) l=action( 1 ) print (l( 2 )) #3 action1=( lambda x: lambda y:x+y) a=action1( 11 ) print (a( 22 )) #33 #Commonly used for callback handler def onPress(s): print (s) import sys from tkinter import Button, mainloop #x=Button(text='Press me', command=lambda :sys.stdout.write('spam\n')) x=Button(text='Press me', command=lambda : onPress('aaaaaa')) x.pack() mainloop ()
python anonymous function lambda
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325999622&siteId=291194637
Recommended
Ranking