【Python】内置高阶函数

高阶函数就是函数接受的参数是另一个函数

  • Map

  1. Map是python 内置的高阶函数,其可以传入俩个参数,第一个参数是函数,第二个参数是一个Iterable例如list。
    def aa(a):
        return a*a
    r=map(aa,[1,2,3,4])

     

  2. Map的返回值是一个Iterator需要使用list 或者for 输出所有元素。
     print([a for a in map(lambda cc:cc+cc,[1,2,3,4])])

     

  • Reduce

  1. 主要是用于聚合操作

    from functools import reduce
    
    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    
    def char2num(s):
        return DIGITS[s]
    
    def str2int(s):
        return reduce(lambda x, y: x * 10 + y, map(char2num, s))
  • filter

  1. 和map 类似都是接收俩个参数一个是函数一个参数是序列,filter 是用于对序列的过滤,通过判断true 或者是false 来决定元素的去留。
    def _odd_iter():
        n = 1
        while True:
            n = n + 2
            yield n
    def _not_divisible(n):
        return lambda x: x % n > 0
    def primes():
        yield 2
        it = _odd_iter() # 初始序列
        while True:
            n = next(it) # 返回序列的第一个数
            yield n
            it = filter(_not_divisible(n), it) # 构造新序列
    if __name__ == '__main__':
        print([a for a in d(9)])
        print([a for a in map(lambda cc:cc+cc,[1,2,3,4])])
        # print([a for a in reduce(lambda a,b:a*10+b,map(lambda cc:cc*2+cc,range(6)))])
        for n in primes():
            if n < 1000:
                print(n)
            else:
                break

     

  • sorted

  1. 是一个进行用来排序的函数
    print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))

     

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值