您的位置:首页 > 编程语言 > Python开发

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

2015-11-26 17:27 736 查看
#!/usr/bin/python
#encoding=utf-8

def back():
return 1,2, "xxx"

#python 可变参数
def test(*param):
print "参数的长度是:%d" % len(param)
print "第二个参数是:%s"  % param[1]
print "第一个参数是:%s"  % param[0]

test(1, "xx", '888')
#test((22, 'xxfff'))
#可变参数结合关键字参数  python2.x 是不允许的,python3.x是ok的
def test2(*param, exp=0):
print  "参数的长度是:%d" % len(param)
print "第二个参数是:%s"  % param[1]
print "第一个参数是:%s"  % param[0]

test2(6, "xxx", 9, 'xxx', exp=20)
#test2(6, "xxx", 9, 'xxx')

#函数内部修改全局变量
#必须使用关键字global
#否则,函数内部会生成一个同名的局部变量
#切记,切记

#内部/内嵌函数
#fun2是内嵌/内部函数
def fun1():
print "fun1 calling now...."
def fun2():
print "fun2 calling now..."
fun2()

fun1()

def  Funx(x):
def Funy(y):
return x*y
return Funy     #返回函数这一对象(函数也是对象)

i = Funx(5)
i(8)

def Fun1():
x = 3
def Fun2():
nonlocal x
x* = x
return x
return Fun2()

Fun1()

#!/usr/bin/python
#encoding=utf-8

#python3
"""
def fun1():
x = 9
def fun2():
nonlocal x
x *= x
return x
return fun2()

fun1()
"""
#python2
def fun3():
x = [9]
def fun5():
x[0]*=x[0]
return x[0]
return fun5()

fun3()


#!/usr/bin/python
#encoding=utf-8

def ds(x):
return 2*x +1

#x相当于函数的参数,冒号后面相当于函数的返回值
g = lambda x: 2*x + 1
g(5)        #lambda的使用

g1 = lambda x,y: x+y

#eif:内置函数
list(filter(None, [1, 0, False, True]))
#[1, True]

def odd(x):
return x%2

temp = range(10)    #可迭代对象
list(filter(odd, temp))
#等价于
list(filter(lambda x:x%2, range(10)))

#map
list(map(lambda x: x*2, range(10)))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: