zoukankan      html  css  js  c++  java
  • Python老男孩 day16 函数(八) map函数、filter函数、reduce函数

    https://www.cnblogs.com/linhaifeng/articles/6113086.html

     ——————————————————————————————————————

    1.Map函数

    #实现列表每个数字变为它的平方

    array=[1,3,4,71,2]
    
    ret=[]
    
    for i in array:
        ret.append(i**2)
    
    print(ret)

     运行结果:

    [1, 9, 16, 5041, 4]

    #如果我们有一万个列表,那么你只能把上面的逻辑定义成函数

    def map_test(array):
        ret=[]
        for i in array:
            ret.append(i**2)
        return ret
    
    print(map_test(array))

     运行结果:

    [1, 9, 16, 5041, 4]

     #如果我们的需求变了,不是把列表中每个元素都平方,还有加1,减1,那么可以这样

    def add_num(x):
        return x+1
    
    def map_test(func,array):
        ret=[]
        for i in array:
            ret.append(func(i))
        return ret
    
    print(map_test(add_num,array))
    #可以使用匿名函数
    print(map_test(lambda x:x-1,array))

     运行结果:

    [2, 4, 5, 72, 3]
    [0, 2, 3, 70, 1]

    #map(func,iter) 第一个参数可以是lambda,也可以是函数;第二个参数为可迭代对象

    array=[1,3,4,71,2]
    
    res=map(lambda x:x-1,array)
    
    print(list(res))
    
    运行结果:
    [0, 2, 3, 70, 1]      #结果与上面我们自己写的map_test实现的一样
    
    
    msg='linhaifeng'
    print(list(map(lambda x:x.upper(),msg)))
    
    运行结果:
    ['L', 'I', 'N', 'H', 'A', 'I', 'F', 'E', 'N', 'G']

     #上面就是map函数的功能,map得到的结果是可迭代对象

    2.filter函数

    需求:取出不带sb的人名

    movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
    
    def filter_test(array):
        ret=[]
        for p in array:
            if not p.startswith('sb'):
                   ret.append(p)
        return ret
    
    res=filter_test(movie_people)
    print(res)

    运行结果:
    ['linhaifeng']

    优化版:

    movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
    
    def sb_show(n):
        return n.endswith('sb')
    
    def filter_test(func,array):
        ret=[]
        for p in array:
            if not func(p):
                   ret.append(p)
        return ret
    
    res=filter_test(sb_show,movie_people)
    print(res)

    运行结果:
    ['linhaifeng']

    最终版:

    movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
    
    思路:
    # def sb_show(n):
    #     return n.endswith('sb')
    #--->lambda n:n.endswith('sb')
    
    def filter_test(func,array):
        ret=[]
        for p in array:
            if not func(p):
                   ret.append(p)
        return ret
    
    res=filter_test(lambda n:not n.endswith('sb'),movie_people)
    print(res)

    运行结果:
    ['linhaifeng']

    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))

    运行结果:
    <filter object at 0x0000021842EFEB00>
    ['linhaifeng']

    3.reduce函数

    需求:求和

    num_l=[1,2,3,100]
    
    res=0
    for num in num_l:
        res+=num
    
    print(res)
    
    运行结果:
    106
    num_l=[1,2,3,100]
    def reduce_test(array):
        res=0
        for num in array:
            res+=num
        return res
    
    print(reduce_test(num_l))
    
    运行结果:
    106
    num_l=[1,2,3,100]
    
    # def multi(x,y):
    #     return x*y
    # lambda x,y:x*y
    
    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))
    
    运行结果:
    600
    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))
    
    运行结果:
    60000

    #reduce函数

    from functools import reduce   #需先倒入模块
    
    num_l=[1,2,3,100]
    
    print(reduce(lambda x,y:x+y,num_l,1))
    print(reduce(lambda x,y:x+y,num_l))
    
    运行结果:
    107
    106

    小结:

    # 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)))

    运行结果:
    [{'name': 'linhaifeng', 'age': 18}]

    #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)))
    
    运行结果:
    5050
    5050
  • 相关阅读:
    论工作动力的来源是什么?答案是来自于实现自己的梦想
    向梦想者致敬
    内置函数,递归函数,模块与包,开发目录规范
    迭代器,生成器
    闭包函数,装饰器,语法糖
    函数对象,名称空间及查找,作用域
    函数调用与参数
    字符编码
    文件处理
    python 11.5数据类型及常用方法
  • 原文地址:https://www.cnblogs.com/zhuhemin/p/9116069.html
Copyright © 2011-2022 走看看