函数式编程
把函数本身作为参数传入另一个函数,还允许返回一个函数
Lambda:
(lambda x, y : x+y)(1,2)
1. lambda 部分 (lambda x, y : x+y), 输入值 (1,2)
2.结果是 (1+2 = )3
3.其他写法
# lambda匿名函数
la = lambda a,b,c:a*b*c
print la(1,2,3)
# 返回结果为6
Filter:
>>> list(filter(lambda x: x>5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
[6, 7, 8, 9, 10]
1.将符合规则得入参过滤出来,而不是计算结果。
2.python3中filter输出得是迭代对象,需要list化而python2中不需要。
Map:
>>>list(map(lambda x,y:x*y-4,range(3),[8,9,10]))
[-4, 5, 16]
1. 函数部分需要几个参数就得传入几组入参,
2.python2中不同入参的数量要对应,python3不需要,只要有一组入参用完就结束运行了。
3.python3中ma'p输出得是迭代对象,需要list化而python2中不需要。
Redus:
>>> from functools import reduce
>>> arr = [1, 2, 3, 4, 5, 6]
>>> reduce(lambda x, y : x+y, arr)
21
1.Reduce对入参顺序迭代调用function。function接收的参数个数只能为2,先把sequence中第一个值和第二个值当参数传给function,再把function的返回值和第三个值当参数传给function,然后只返回一个结果。也就是说计算过程是1+2 =3 , 3+3=6,,,。
2.reduce() 函数已经被从全局名字空间里移除了,它现在被放置在fucntools 模块里。
3.初始值,如果初始值是10,计算过程是 10 + 1=11, 11+2=13,,,,,,,
>>> from functools import reduce
>>> arr = [1, 2, 3, 4, 5, 6]
>>> reduce(lambda x, y : x+y, arr, 10)
31