Anonymous function
With the ability to create an anonymous lambda function, this function takes its name omitted by standard procedures def function declaration.
grammar
lambda [arg1 [,arg2,.....argn]]:expression
how to use
- When we define a normal function like this
def add(a,b):
return a+b
- Using lambda define an anonymous function like this
add = lambda a,b:a+b # 和上面函数功能一样
You can call the normal way. lambda expression can receive any number of parameters but only a return value of the expression.
use
1 as described above can be simplified code
2. anonymous function passed as a parameter
- As a custom function parameters are passed
def test(a, b, func):
result = func(a, b)
print(result)
func_new = input("请输入一个匿名函数:")
# eval()将字符串str当成有效的表达式来求值并返回计算结果。
func_new = eval(func_new)
test(11, 22, func_new)
"""
输出结果:
请输入一个匿名函数:lambda a,b:a+b
33
"""
- Built-in functions are passed as parameters
, for example: a list of dictionary sorted according to specified keywords
stus = [
{"name":"zhangsan", "age":18},
{"name":"lisi", "age":19},
{"name":"wangwu", "age":17}
]
stus.sort(key = lambda x:x['age'])
for stu in stus:
print(stu)
"""
输出结果:
{'name': 'wangwu', 'age': 17}
{'name': 'zhangsan', 'age': 18}
{'name': 'lisi', 'age': 19}
"""