Python function -2 anonymous function

Anonymous function
when we create a function, in some cases, do not need to explicitly define the function directly into the anonymous function more convenient. This saves us the trouble of naming as a function of their brains, but also write a lot less code and many programming languages provide this feature.

Python language using the lambda keyword to create an anonymous function.

The so-called anonymous, that is no longer defined function uses a standard form of such def statement.

  1. Just a lambda expression, rather than a block of code, the function thereof is much simpler than def.
  2. You can only package a limited logic lambda expressions.
  3. lambda function has its own namespace.
    For example: lambda x: x * x. It corresponds to the following function:
def f(x):
    return x*x
关键字lambda表示匿名函数,冒号前面的x表示函数参数,x*x是执行代码

Anonymous functions can be only one expression, can not write without a return statement, the result of an expression is its return value. Anonymous function has no name, do not worry about the function name conflict, meaning saving space. In addition, an anonymous function is a function object, you can put anonymous function assigned to a variable, and then use a variable to call the function:

f = lambda x: x * x
f
<function <lambda> at 0x3216fef44>
f(6)
36
也可以把匿名函数作为别的函数的返回值返回
def count(i,j):
    return lambda : i*j

f = count(6,7)
print(f())

Application anonymous function
to sort the list of dictionary

lis = [1,-2,4,-3]
lis.sort(key=abs)
print(lis)

infors = [{'name':'cangls','age':18},{'name':'bols','age':20},{'name':'jtls','age':25}]

infors.sort(key = lambda x:x['name'])

print(infors)

Anonymous functions as arguments

def test(a,b,func):
    result = func(a,b)
    return result
    
nums = test(11,22,lambda x,y:x+y)
print(nums)

Guess you like

Origin www.cnblogs.com/sakura579/p/12244031.html