zoukankan      html  css  js  c++  java
  • 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)))
  • 相关阅读:
    【bzoj2500】幸福的道路 树形dp+单调队列
    【ARC069F】Flags 2-sat+线段树优化建图+二分
    【bzoj2437】[Noi2011]兔兔与蛋蛋 二分图最大匹配+博弈论
    剑指offer——树的子结构
    剑指offer——反转链表
    腾讯算法岗面试算法题——计数排序
    作业帮面试题
    剑指offer——重建二叉树
    剑指offer——二维数组中的查找
    删除链表中重复的结点
  • 原文地址:https://www.cnblogs.com/raitorei/p/11802859.html
Copyright © 2011-2022 走看看