Python Lambda
Python Lambda
Python lambda:
- an expression form that generates function objects.
- anonymous (i.e., unnamed) function
lambda is designed for coding simple functions
def handles larger tasks
'''lambda Basics'''
# ------- lambda expression ------- #
f = lambda x, y, z: x + y + z # returns a function that can optionally be assigned a name
# ------- def statements ------- #
def func(x, y, z): # always assigns the new function to the name automatically
return x + y + z
print(func(2, 3, 4) == f(2, 3, 4))
'''Why Use lambda?'''
# ------- lambda expression ------- #
# provide code proximity: if only be used in a single context and not used anywhere else
# stuff small pieces of executable code into places where statements are illegal syntactically
L1 = [lambda x: x ** 2, # inline function definition
lambda x: x ** 3,
lambda x: x ** 4] # a list of three callable functions
for f in L1:
print(f(2)) # prints 4, 8, 16
print(L1[0](3)) # prints 9
# ------- def statements ------- #
def func1(x): return x ** 2 # define named functions
def func2(x): return x ** 3 # function definitions outside the context of intended use (which might be hundreds of lines away)
def func3(x): return x ** 4
L2 = [func1, func2, func3] # reference by name
for f in L2:
print(f(2)) # prints 4, 8, 16
print(L2[0](3)) # prints 9 相关推荐
meylovezn 2020-09-21
mmmjyjy 2020-07-16
typhoonpython 2020-06-11
x青年欢乐多 2020-06-06
Stranger 2020-05-16
PythonMaker 2020-04-22
QianYanDai 2020-04-18
千锋 2020-04-11
SDUTACM 2020-03-05
fly00love 2020-03-05
wklken的笔记 2020-01-30
GhostLWB 2020-01-30
sulindong0 2020-01-19
chinademon 2020-01-12
mieleizhi0 2020-01-11
samsai00 2020-01-06