python 内部函数,以及lambda,filter,map等内置函数

 1 #!/usr/bin/python 
 2 #encoding=utf-8
 3 
 4 def back():
 5     return 1,2, "xxx"
 6 
 7 #python 可变参数
 8 def test(*param):
 9     print "参数的长度是:%d" % len(param)
10     print "第二个参数是:%s"  % param[1]
11     print "第一个参数是:%s"  % param[0]
12 
13 test(1, "xx", '888')
14 #test((22, 'xxfff'))
15 #可变参数结合关键字参数  python2.x 是不允许的,python3.x是ok的
16 def test2(*param, exp=0):
17     print  "参数的长度是:%d" % len(param)
18     print "第二个参数是:%s"  % param[1]
19     print "第一个参数是:%s"  % param[0]
20 
21 test2(6, "xxx", 9, 'xxx', exp=20)
22 #test2(6, "xxx", 9, 'xxx')
23 
24 #函数内部修改全局变量
25 #必须使用关键字global
26 #否则,函数内部会生成一个同名的局部变量
27 #切记,切记
28 
29 #内部/内嵌函数
30 #fun2是内嵌/内部函数
31 def fun1():
32     print "fun1 calling now...."
33     def fun2():
34         print "fun2 calling now..."
35     fun2()
36 
37 fun1()
38 
39 def  Funx(x):
40     def Funy(y):
41         return x*y
42     return Funy     #返回函数这一对象(函数也是对象)
43 
44 i = Funx(5)
45 i(8)
46 
47 def Fun1():
48     x = 3
49     def Fun2():
50         nonlocal x
51         x* = x
52         return x
53     return Fun2()
54 
55 Fun1()
56 
57 #!/usr/bin/python 
58 #encoding=utf-8
59 
60 #python3
61 """
62 def fun1():
63     x = 9
64     def fun2():
65         nonlocal x
66         x *= x
67         return x
68     return fun2()
69 
70 fun1()
71 """
72 #python2 
73 def fun3():
74     x = [9] 
75     def fun5():
76         x[0]*=x[0]
77         return x[0]
78     return fun5()
79 
80 fun3()
 1 #!/usr/bin/python 
 2 #encoding=utf-8
 3 
 4 def ds(x):
 5     return 2*x +1
 6 
 7 #x相当于函数的参数,冒号后面相当于函数的返回值
 8 g = lambda x: 2*x + 1 
 9 g(5)        #lambda的使用
10 
11 g1 = lambda x,y: x+y 
12 
13 #eif:内置函数
14 list(filter(None, [1, 0, False, True]))
15 #[1, True]
16 
17 def odd(x):
18     return x%2 
19 
20 temp = range(10)    #可迭代对象
21 list(filter(odd, temp))
22 #等价于
23 list(filter(lambda x:x%2, range(10)))
24 
25 #map
26 list(map(lambda x: x*2, range(10)))
原文地址:https://www.cnblogs.com/chris-cp/p/4998408.html