函数式编程技术lambda、map、filter、reduce

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值