|  | 
 
| 
本帖最后由 尘鸯 于 2017-9-18 15:46 编辑
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  
 函数--2
 
 内嵌函数和闭包
 内嵌函数:在函数中再次创建函数
 例:def test1():
 print('test1()正被调用...')
 def test2():
 print('test2()正被调用......')
 test2()
 调用test1()函数
 输出:test1()正被调用...
 test2()正被调用......
 内嵌的函数只能在当前的函数中随意调用,在外部无法调用。test2()只能在test1()中被随意调用,在外部无法调用test2()
 例:def test1():
 print('test1()正被调用...')
 def test2():
 print('test2()正被调用......')
 test2()
 调用test2()函数
 错误:test2()未被定义
 
 闭包:如果在一个内部函数里对外部作用域的变量(不是对全局变量)进行了引用,则这个内部函数就是一个闭包
 例:def test1(x):
 def test2(y):
 return x * y
 return test2()
 调用函数:test(4)(5)
 输出:20
 
 
 lambda表达式
 例1:def test1(x):
 return 2 * x
 调用函数:test1(5)
 输出: 10
 lambda表达式: g = lambda x : 2 * x
 g(5)
 输出:10
 
 例2:def test2(x,y)
 return x + y
 调用函数:test2(2 + 3)
 输出: 5
 lambda表达式:g = lambda x , y : x + y
 g(2,3)
 输出:5
 
 BIF:filter(function or None , iterable)、map(func , *iterable)
 
 filter():将iterable作为参数传入到func中运行,如果func为true,则返回当前值;如果第一个参数为None,则返回iterable中true的值
 map():将*iterable作为参数传入到func中运行,并返回结果
 例1:list(filter(lambda x : x % 2 , range(10)))
 输出:[1 , 3 , 5 , 7 , 9]
 例2:list(map(lambda x : x + 2 , range(10)))
 输出:[2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12]
 | 
 |