• 16python的map函数,filter函数,reduce函数


    map

    num_l = [1,6,8,9]
    def map_test(func,array):
        ret = []
        for i in array:
            res = func(i)
            ret.append(res)
        return ret
    def jia(x):
        return x+1
    
    #内置函数
    print(map_test(lambda  x:x+1,num_l))
    
    print(map_test(jia,num_l))
    
    #只能迭代一次
    # res = map(lambda  x:x+1,num_l)
    # for i in res:
    #     print(i)
    # print(list(res))

    filter

    #filter函数
    movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
    print(filter(lambda n:not n.endswith('sb'),movie_people))
    
    
    res=filter(lambda n:not n.endswith('sb'),movie_people)
    print(list(res))
    
    
    print(list(filter(lambda n:not n.endswith('sb'),movie_people)))

    reduce

    # def reduce_test(func,array):
    #     res=array.pop(0)
    #     for num in array:
    #         res=func(res,num)
    #     return res
    #
    # print(reduce_test(lambda x,y:x*y,num_l))
    
    num_l=[1,2,3,100]
    def reduce_test(func,array,init=None):
        if init is None:
            res=array.pop(0)
        else:
            res=init
        for num in array:
            res=func(res,num)
        return res
    
    print(reduce_test(lambda x,y:x*y,num_l,100))
    #处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来一样
    # map()
    
    #filter遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来
    
    people=[
        {'name':'alex','age':1000},
        {'name':'wupei','age':10000},
        {'name':'yuanhao','age':9000},
        {'name':'linhaifeng','age':18},
    ]
    print(list(filter(lambda p:p['age']<=18,people)))
    
    
    #reduce:处理一个序列,然后把序列进行合并操作
    from functools import reduce
    print(reduce(lambda x,y:x+y,range(100),100))
    print(reduce(lambda x,y:x+y,range(1,101)))
  • 相关阅读:
    带你剖析WebGis的世界奥秘----点和线的世界
    XML解析
    Java-工厂设计模式
    分享:软件包和文档
    启航,新开始
    docker容器网络通信原理分析(转)
    【好书分享】容器网络到kubernetes网络
    go语言接受者的选取
    go语言的unsafe包(转)
    protocol buffers生成go代码原理
  • 原文地址:https://www.cnblogs.com/raitorei/p/11802859.html
Copyright © 2020-2023  润新知