码迷,mamicode.com
首页 > 编程语言 > 详细

Python Lambda

时间:2020-02-21 11:25:31      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:asi   expr   orm   des   return   turn   class   syn   inline   

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

Python Lambda

标签:asi   expr   orm   des   return   turn   class   syn   inline   

原文地址:https://www.cnblogs.com/bit-happens/p/12340618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!