函数(二)---函数的嵌套、递归函数、匿名函数
1. 函数的嵌套
函数内部调用其他函数
def test1(): print("*" * 50) def test2(): print("-" * 50) # 函数的嵌套调用 test1() test2() """ 运行结果: -------------------------------------------------- ************************************************** """
函数内部定义函数
def test_1(): print('This is test1') def test_2(): print('This is test2') test_2() test_1() """ 运行结果: This is test1 This is test2 """
def test_1(): print('This is test1') def test_2(): print('This is test2') test_2() test_2() # 运行结果:NameError: name 'test_2' is not defined, 因为test_2()是在test_1()内部定义的
如果要在函数内部修改外边的值, 需要用关键字nonlocal来修改
def test_1(): a = 100 print('This is test1') print(f'This is test_1 variate a {a}') def test_2(): a = 1 print('This is test2') print(f'This is test_2 variate a {a}') test_2() print(f'This is test_1 variate a {a}') test_1() """ 运行结果: This is test1 This is test_1 variate a 100 This is test2 This is test_2 variate a 1 This is test_1 variate a 100 """ def test_1(): a = 100 print('This is test1') print(f'This is test_1 variate a {a}') def test_2(): nonlocal a a = 1 print('This is test2') print(f'This is test_2 variate a {a}') test_2() print(f'This is test_1 variate a {a}') test_1() """ 运行结果: This is test1 This is test_1 variate a 100 This is test2 This is test_2 variate a 1 This is test_1 variate a 1 """
2. 递归函数
一个函数在内部调用自身本身,这个函数就是递归函数。
递归函数特性:
1. 必须有一个明确的结束条件;
2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少
3. 相邻两次重复之间有紧密的联系,前一次要为后一次做准备(通常前一次的输出就作为后一次的输入)。
4. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)
def fact(n): if n == 1: return 1 else: return n * fact(n-1) result = fact(5) print(result) # 运行结果: 120 result = fact(1000) print(result) # 运行结果:RecursionError: maximum recursion depth exceeded in comparison, 超出了最大递归深度
3. 匿名函数
1. 什么是匿名函数?
在Python中,不通过def来声明函数名字,而是通过lambda关键字来定义的函数称为匿名函数。
2. lambda表达式 lambda 参数 :表达式
# 常规函数 def add(x, y): return x + y result = add(5, 3) print(result) # 匿名函数一: result = lambda x,y : x+y print(result(5, 3)) # 匿名函数二 result = (lambda x, y : x + y)(5,3) print(result)
3. 匿名函数与常规函数的区别
lambda是一个表达式,并不是一个语句(表达式:用一系列‘公式’去表达一个东西(如:x +2), 语句:完成了某些功能(x = 2, print('hello') ))
lanbda的主体是只有一行的简单表达式,并不能扩展成一个多行代码块
lambda表达式的应用:
# 列表解析式 result = [x * 2 for x in range(10)] print(result) # 创建一个函数, 再使用列表解析式 def multiple(x): return x *2 print([multiple(x) for x in range(10)]) # lambda表达式 print([(lambda x: x * 2) (x) for x in range(10)])
# 结合sort()函数 # 常规函数 list_val = [(1,3), (2, 3), (3,1)] def take_second(list_val): return list_val[1] list_val.sort(key=take_second, reverse= True) print(list_val) # lambda表达书 list_val = [(1,3), (2, 3), (3,1)] list_val.sort(key=lambda x : x[1], reverse=True) print(list_val)

浙公网安备 33010602011771号