Python3 anonymous functions and lambda Detailed example of use

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_39377418/article/details/99336665

Outline

       Anonymous function, the name suggests that there is no difference between the maximum function of function, and def defined name that returns the function itself after an anonymous function creates a return to the return value, the return value is the result of the expression itself, but def created after the assignment to a variable name, in Python, we create an anonymous function using the keyword lambda, the lambda expression is in the form of an anonymous function:

  • lambda arg1,arg2,.....argn:expression

The following is a characteristic of some of lambda:

lambda is an expression, not a statement that we can use in any scene as lambda expressions can be used.
lambda is an expression of the body, and that is defined as a function def, lambda also has the function body, but the body is just a lambda expression, so its use functions subject to greater restrictions.

lambda use

No-argument anonymous function

# 可以将lambda直接传递给一个变量,像调用一般函数一样使用

B = lambda :True
print(B())

# 等价于
def BF():
    return True
print(BF())

# 输出结果
"""
True
True
"""

There are anonymous function parameters

lambda supports multiple parameters

1. Parameter Default None

two_sum = lambda x, y: x + y
print(two_sum(1,2))

# 等同于:
def two_sum(x, y):
    return x + y
print(two_sum(1,2))

# 输出
"""
3
3
"""

2. Parameters with default values

sum_with_100 = lambda x, y=100: x + y
print(sum_with_100(200))

# 等同于:
def sum_with_100(x, y=100): return x + y
print(sum_with_100(200))

# 输出
"""
300
300
"""

Parameter passing from behind

The previous example we will assign a variable lambda anonymous function, def embodiment functions similarly defined by transmission parameters, we can pass parameters directly behind lambda:

two_sum = (lambda x, y: x + y)(3, 4)
print(two_sum)

# 输出
"""
7
"""

Nest

The normal function nested lambda, lambda value of the function itself as the return build a simple closure

def sum(x):
    return lambda y: x + y
sum_with_100 = sum(100)
result = sum_with_100(200)
print(result)

# 输出
"""
300
"""

Some examples of use

1. The two combined in the minimum valued triplet expression evaluation


lower = lambda x,y: x if x<y else y
print(lower(7,100))

# 输出
"""
7
"""

2. The key to a sort of dictionary

d = [{"order": 3}, {"order": 1}, {"order": 2}]
# 根据order键值排序
d.sort(key=lambda x: x['order'])
print(d)

# 输出
"""
[{'order': 1}, {'order': 2}, {'order': 3}]
"""

 

Guess you like

Origin blog.csdn.net/qq_39377418/article/details/99336665