Introduction and use of python anonymous function

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

  1. When we define a normal function like this
def add(a,b):
	return a+b
  1. 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

  1. 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
"""
  1. 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}
"""
Published 44 original articles · won praise 8 · views 2475

Guess you like

Origin blog.csdn.net/qq_39659278/article/details/99695261