python基础—函数式编程
函数式编程
1.不可变数据
2.第一类对象
3.尾调用优化(尾递归)
1.高阶函数
满足两个条件任意一个为高阶函数:
1.函数的传入参数是一个函数名
2.函数的返回值是一个函数
#非函数式 a = 1 def test():global aa += 1return a test() print(a)#函数式 n=1 def test1():return n+1 print(test1())
把函数当作参数传给另一个函数
def foo(n):print(n) def bar(name):print('My name is %s'%name)foo(bar('alex'))
My name is alex None
返回值中包含函数
def foo():print('from foo')return bar
def bar():print('from bar')foo()() from foo
from bar def foo():print('from foo')return foo foo()()
from foo from foo
2.尾调用
在函数的最后一步调用另外一个函数(最后一行不一定是函数的最后一步)
尾调用的关键在于函数的最后一步调用别的函数,根据函数即变量的定义,定义a函数,b内调用函数c,在内存中形成一个调用记录,又称为调用栈,
用于保存调用位置以及变量信息,即a->b->c,直到c返回结果给b,c的调用记录才会消失,b返回a,b的调用结果消失,a返回结果,a的调用记录消失,所有的调用
记录都是“”先进后出”,形成一个‘’调用栈‘’。
3.map函数
处理序列中每个元素,得到的结果是一个“列表”,该“列表”元素个数及位置与原来一样
num = [1,2,3,4] def add(x):return x+1def map_test(func,array):ret = []for i in array:res = func(i)ret.append(res)return ret print(map_test(add,num))
[2, 3, 4, 5]
配合匿名函数
num = [1,2,3,4] def map_test(func,array):ret = []for i in array:res = func(i)ret.append(res)return ret print(map_test(lambda x:x+1,num))
num = [1,2,3,4] def add(x):return x+1 msg='xiaob' print(list(map(lambda x:x+1,num))) print(tuple(map(lambda x:x.upper(),msg))) print(list(map(add,num)))
[2, 3, 4, 5] ('X', 'I', 'A', 'O', 'B') [2, 3, 4, 5]
filter函数
遍历序列中每个元素,判断每个元素得到一个布尔值,如果是True则留下来
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)
['linhaifeng']
def sb_show(n):return n.endswith('sb')res=filter(sb_show,movie_people) print(list(res)) res = filter(lambda n:not n.endswith('sb'),movie_people) print(list(res)) print(list(filter(lambda n:not n.endswith('sb'),movie_people)))
['alex_sb', 'wupeiqi_sb', 'yuanhao_sb'] ['linhaifeng'] ['linhaifeng']
people = [{'name':'alex','age':1000,'name':'seven','age':1000,'name':'Christian','age':18}]
print(list(filter(lambda x:x['age']<=18,people))) [{'name': 'Christian', 'age': 18}]
reduce
处理一个序列,然后把序列进行合并
num = [1,2,3,10] def multi(x,y):return x*y def reduce_test(func,array,init=None):if init is None:res = array.pop(0)else:res = initfor i in array:res = func(res,i)return res
print(reduce_test(multi,num,10))
600
from functools import reduce num = [1,2,3,10] print(reduce(lambda x,y:x*y,num,2))
120
转载于:https://www.cnblogs.com/huiyichanmian/p/8807912.html
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
