python开发学习 day16-python函数(作用域,函数式编程,匿名函数。。。)
一、函数作用域
# def test1(): # print('in the test1') # def test(): # print('in the test') # return test1 # # # print(test) # res=test() # print(res()) #test1() #函数的作用域只跟函数声明时定义的作用域有关,跟函数的调用位置无任何关系 # name = 'alex' # def foo(): # name='linhaifeng' # def bar(): # # name='wupeiqi' # print(name) # return bar # a=foo() # print(a) # a() #bar() name='alex' def foo(): name='lhf' def bar(): name='wupeiqi' print(name) def tt(): print(name) return tt return bar # bar=foo() # tt=bar() # print(tt) # tt() r1 = foo() r2 = r1() # tt r3 = r2() foo()()()
二、匿名函数
# lambda x:x+1 def calc(x): return x+1 res=calc(10) print(res) print(calc) print(lambda x:x+1) func=lambda x:x+1 print(func(10)) name='alex' #name='alex_sb' def change_name(x): return name+'_sb' res=change_name(name) print(res) func=lambda x:x+'_sb' res=func(name) print('匿名函数的运行结果',res) # func=lambda x,y,z:x+y+z # print(func(1,2,3)) name1='alex' name2='sbalex' name1='supersbalex' # def test(x,y,z): # return x+1,y+1 #----->(x+1,y+1) # lambda x,y,z:(x+1,y+1,z+1)
三、函数式编程(高阶函数)
编程方法论
1.面向过程 没有返回值
2.函数式
3.面向对象
#高阶函数 1。函数接收的参数是一个函数名 2#返回值中包含函数 # 把函数当作参数传给另外一个函数 # def foo(n): #n=bar # print(n) # # def bar(name): # print('my name is %s' %name) # # # foo(bar) # # foo(bar()) # foo(bar('alex')) #返回值中包含函数 def bar(): print('from bar') def foo(): print('from foo') return bar n=foo() n() def hanle(): print('from handle') return hanle h=hanle() h() def test1(): print('from test1') def test2(): print('from handle') return test1()
四、函数式编程卫递归调用优化(基本用不到)
#非尾递归 def cal(seq): if Len(seq) == 1 return seq[0] head,*tail = seq return head+cal(tail) #尾递归 def cal(l): print(l) if len(l) == 1: return l[0] first,second,*args=1 l[0] = first+second l.pop(1) return cal(l) x=cal([for I in range(10)]) print(x)
尾递归的实现,往往需要修改递归函数,确保最后一步调用自身
要做到这一点,就是要把函数内部变量编程参数传递,如上例,但是带来的一个问题是,改写后的函数需要新增一个形参total,这样你在做5到阶乘的时候,编程了factorial(5,1) 这个让人费解。
解决方法一,定义默认参数
五、函数式编程中的函数(map,reduce,filter,及高阶函数)
5.1 map函数
# num_l=[1,2,10,5,3,7] # num1_l=[1,2,10,5,3,7] # ret=[] # for i in num_l: # ret.append(i**2) # # print(ret) # def map_test(array): # ret=[] # for i in num_l: # ret.append(i**2) # return ret # # ret=map_test(num_l) # rett=map_test(num1_l) # print(ret) # print(rett) num_l=[1,2,10,5,3,7] #lambda x:x+1 def add_one(x): return x+1 #lambda x:x-1 def reduce_one(x): return x-1 #lambda x:x**2 def pf(x): return x**2 def map_test(func,array): ret=[] for i in num_l: res=func(i) #add_one(i) ret.append(res) return ret # print(map_test(add_one,num_l)) # print(map_test(lambda x:x+1,num_l)) # print(map_test(reduce_one,num_l)) # print(map_test(lambda x:x-1,num_l)) # print(map_test(pf,num_l)) # print(map_test(lambda x:x**2,num_l)) #终极版本 def map_test(func,array): #func=lambda x:x+1 arrary=[1,2,10,5,3,7] ret=[] for i in array: res=func(i) #add_one(i) ret.append(res) return ret print(map_test(lambda x:x+1,num_l)) res=map(lambda x:x+1,num_l) print('内置函数map,处理结果',res) # for i in res: # print(i) print(list(res)) print('传的是有名函数',list(map(reduce_one,num_l))) msg='linhaifeng' print(list(map(lambda x:x.upper(),msg)))
5.2 reduce函数
# from functools import reduce # num_l=[1,2,3,100] # res=0 # for num in num_l: # res+=num # # print(res) # num_l=[1,2,3,100] # def reduce_test(array): # res=0 # for num in array: # res+=num # return res # # print(reduce_test(num_l)) # num_l=[1,2,3,100] # def multi(x,y): # return x*y #lambda x,y:x*y # def reduce_test(func,array): # res=array.pop(0) # for num in array: # res=func(res,num) # return res # # print(reduce_test(lambda x,y:x*y,num_l)) num_l=[1,2,3,100] def reduce_test(func,array,init=None): if init is None: res=array.pop(0) else: res=init for num in array: res=func(res,num) return res print(reduce_test(lambda x,y:x*y,num_l,100)) #reduce函数 from functools import reduce num_l=[1,2,3,100] print(reduce(lambda x,y:x+y,num_l,1)) print(reduce(lambda x,y:x+y,num_l))
5.3 filter函数
# movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao'] # def filter_test(array): # ret=[] # for p in array: # if not p.startswith('sb'): # ret.append(p) # return ret # # res=filter_test(movie_people) # print(res) # movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb'] # def sb_show(n): # return n.endswith('sb') # # def filter_test(func,array): # ret=[] # for p in array: # if not func(p): # ret.append(p) # return ret # # res=filter_test(sb_show,movie_people) # print(res) #终极版本 movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb'] # def sb_show(n): # return n.endswith('sb') #--->lambda n:n.endswith('sb') def filter_test(func,array): ret=[] for p in array: if not func(p): ret.append(p) return ret res=filter_test(lambda n:n.endswith('sb'),movie_people) print(res) #filter函数 movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb'] print(filter(lambda n:not n.endswith('sb'),movie_people)) res=filter(lambda n:not n.endswith('sb'),movie_people) print(list(res)) print(list(filter(lambda n:not n.endswith('sb'),movie_people)))
六、内置函数
# print(abs(-1)) # print(abs(1)) # # print(all([1,2,'1'])) # print(all([1,2,'1',''])) # print(all('')) # print(any([0,''])) # print(any([0,'',1])) # print(bin(3)) #空,None,0的布尔值为False,其余都为True # print(bool('')) # print(bool(None)) # print(bool(0)) # name='你好' # print(bytes(name,encoding='utf-8')) # print(bytes(name,encoding='utf-8').decode('utf-8')) # # print(bytes(name,encoding='gbk')) # print(bytes(name,encoding='gbk').decode('gbk')) # # print(bytes(name,encoding='ascii'))#ascii不能编码中文 # print(chr(46)) # print(dir(dict)) # print(divmod(10,3)) # dic={'name':'alex'} # dic_str=str(dic) # print(dic_str) #可hash的数据类型即不可变数据类型,不可hash的数据类型即可变数据类型 # print(hash('12sdfdsaf3123123sdfasdfasdfasdfasdfasdfasdfasdfasfasfdasdf')) # print(hash('12sdfdsaf31231asdfasdfsadfsadfasdfasdf23')) # # name='alex' # print(hash(name)) # print(hash(name)) # # # print('--->before',hash(name)) # name='sb' # print('=-=>after',hash(name)) # print(help(all)) # print(bin(10))#10进制->2进制 # print(hex(12))#10进制->16进制 # print(oct(12))#10进制->8进制 # print(isinstance(1,int)) # print(isinstance('abc',str)) # print(isinstance([],list)) # print(isinstance({},dict)) # print(isinstance({1,2},set)) name='哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈粥少陈' # print(globals()) # print(__file__) # # def test(): # age='1111111111111111111111111111111111111111111111111111111111111' # # print(globals()) # print(locals()) # # test() l=[1,3,100,-1,2] print(max(l)) print(min(l))
七、小结
#处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来一样 # map() #filter遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来 people=[ {'name':'alex','age':1000}, {'name':'wupei','age':10000}, {'name':'yuanhao','age':9000}, {'name':'linhaifeng','age':18}, ] print(list(filter(lambda p:p['age']<=18,people))) #reduce:处理一个序列,然后把序列进行合并操作 from functools import reduce print(reduce(lambda x,y:x+y,range(100),100)) print(reduce(lambda x,y:x+y,range(1,101)))

浙公网安备 33010602011771号