lambda:快速定义单行的最小函数,inline的匿名函数
map(function, sequence) :对sequence中的item依次执行function(item),执行结果组成一个List返回
filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回
reduce
python3中取消了全局命名空间中的reduce()函数,将reduced()放到了functools模块中,要使用reduce()的话,要先加载functools.
"""函数式编程技术"""
def inc(x):
def incx(y):
return 2*x+y
return incx
inc2 = inc(2)
inc5 = inc(5)
print(inc2.__name__) # incx 作为函数返回
print(inc2(5)) # 9=2*2+5
print(inc5(5)) # 15=2*5+5
"""lambda:快速定义单行的最小函数,inline的匿名函数"""
g = lambda x:x*2
print(g(3)) # 6
print((lambda x:x*2)(4)) # 8
"""map(function, sequence) :对sequence中的item依次执行function(item),执行结果组成一个List返回"""
name_len = map(len,['qi','yue','july'])
# for i in name_len:
# print(i)
print(list(name_len)) # 连续访问迭代器,第二次开始返回值为空 [2, 3, 4]
squared = list(map(lambda x:x**2,[1,2,3,4,5]))
print(squared) # [1, 4, 9, 16, 25]
"""filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为
True的item组成一个List/String/Tuple(取决于sequence的类型)返回"""
number_list = range(-5,5)
less_than_zero = list(filter(lambda x:x<0,number_list))
print(less_than_zero) # [-5, -4, -3, -2, -1]
less_than_zeroindex = list(map(lambda x:x<0,number_list))
print(less_than_zeroindex) # [True, True, True, True, True, False, False, False, False, False]
"""reduce
python3中取消了全局命名空间中的reduce()函数,将reduced()放到了functools模块中,
要使用reduce()的话,要先加载functools.
"""
from functools import reduce
def add(x,y):return x+y
print(reduce(add,range(1,5),10)) # 20
"""例子:计算正数的平均数"""
from functools import reduce
num =[2, -5, 9, 7, -2, 5, 3, 1, 0, -3, 8]
pnum=list(filter(lambda x:x>0,num)) # [2, 9, 7, 5, 3, 1, 8]
print(reduce(lambda x,y:x+y,pnum)/len(pnum)) # 5.0