1.全局变量和局部变量
1
2
3
4
5
6
7
8
9
|
复制代码 name = "czp" #全局变量 def func ( ) : name = "czp1" #局部变量 print ( name ) func ( ) 运行结果: czp 1 调用func ( ) 函数,程序会先在函数内部找有没有 name 这个变量,如果有,就会调用该 name 的值,而如果没有定义局部变量的话,函数会去找全局 name 。 复制代码 |
01
02
03
04
05
06
07
08
09
10
11
12
|
复制代码 name = "czp" #定义全局变量 def func ( ) : global name 在函数内部,通过 global 关键字,通过局部变量修改全局变量的值 name = "czp1" print ( name ) func ( ) 打印局部变量中 name 的值 print ( name ) 打印全局变量中 name 的值 运行结果: czp 1 czp 1 在运行结果中可以明显看出,通过 global ,在定义局部变量的同时,也修改了全局变量的值 复制代码 |
2.递归函数
01
02
03
04
05
06
07
08
09
10
11
12
13
|
复制代码 def calc ( n ) : print ( n ) if int ( n / 2 ) = = 0 : return n return calc ( int ( n / 2 ) ) 在calc函数中,反复调用calc自身,这样的函数就是递归函数 calc ( 10 ) 运行结果: 10 5 2 1 复制代码 |
3.匿名函数
1
2
3
4
5
|
def calc ( x ) : return x + 1 print ( calc ( 2 ) ) 运行结果: 3 |
1
2
3
4
|
res = lambda x : x + 1 print ( res ( 2 ) ) 运行结果: 3 |
1
2
3
4
5
6
7
8
9
|
复制代码 res = map ( lambda x : x * * 2 , [ 2 , 4 , 6 , ] ) for i in res : print ( i ) 运行结果: 4 16 36 复制代码 |
4.高阶函数
01
02
03
04
05
06
07
08
09
10
11
12
|
复制代码 将函数作为参数传给另一个函数 def foo ( n ) : print ( n ) def bar ( name ) : print ( "my name is %s" % name ) print ( foo ( bar ( "尼古拉斯赵四" ) ) ) 运行结果: my name is 尼古拉斯赵四 None None 返回两个None,因为在foo()和bar()函数中我没有定义retturn。默认返回None 复制代码 |
01
02
03
04
05
06
07
08
09
10
11
12
|
复制代码 将函数作为另一个函数的返回值 def bar ( ) : print ( "from bar" ) def foo ( ) : print ( "from foo" ) return bar foo ( ) ( ) 运行结果: from foo from bar 复制代码 |
4.内置函数
1.map:
01
02
03
04
05
06
07
08
09
10
11
|
复制代码 name = [ 1 , 2 , 3 , 4 ] res = [] 定义一个空列表,用来接收自增一后的值 def calc ( array ) : for i in array : 使用 for 循环,遍历传入列表中的每一个元素 res.append ( i + 1 ) return res print ( calc ( name ) ) 运行结果: [ 2 , 3 , 4 , 5 ] 复制代码 |
01
02
03
04
05
06
07
08
09
10
11
12
13
|
复制代码 def increase ( x ) : return x -1 定义一个自减 1 的函数 name = [ 1 , 2 , 3 , 4 ] res = [] def calc ( func , array ) : 在这里定义两个形参,一个用来传入函数increase,一个用来传入列表 name for i in array : res.append ( increase ( i ) ) return res print ( calc ( increase , name ) ) 运行结果: [ 0 , 1 , 2 , 3 ] 复制代码 |
1
2
3
4
|
name = [ 1 , 2 , 3 , 4 ] print ( list ( map ( lambda x : x + 1 , name ) ) ) 运行结果: [ 2 , 3 , 4 , 5 ] |
2.reduce:
1
2
3
4
5
|
from functools import reduce 必须导入reduce方法 name = [ 1 , 2 , 3 , 4 ] print ( ( reduce ( lambda x , y : x + y , name ) ) ) 函数必须传入两个参数,然后传入 list 。 运行结果: 10 |
def reduce(function, sequence, initial=None) 这个初始值默认为None
1
2
3
4
5
|
from functools import reduce name = [ 1 , 2 , 3 , 4 ] print ( ( reduce ( lambda x , y : x + y , name , 5 ) ) ) 还是上面的例子,我在最后加了初始值 5 (默认是none) 运行结果: 15 |
3.filter
1
2
3
4
|
name = [ "czp" , "cc" , "zp1" ] print ( list ( filter ( lambda n : n.endswith ( "c" ) , name ) ) ) 通过匿名函数判断条件,返回值为真,就会打印成列表的形式 运行结果: ['cc'] |
{:8_507:}