• map、filter、reduce、lambda


    一、map、filter、reduce

      map(fuction , iterable)   映射  对可迭代对象中的每一项,使用函数去改变

      filter(function, iterable)  过滤  可迭代对象中的每一项,放到函数中去计算,如何为真,则留下,构造成一个迭代器,为假则去除

      reduce(fuction,iterable)  减少  把元素中的左边的合并到右边去。

    1.1 map  映射

      官方定义:Return an iterator that applies function to every item of iterable, yielding the results.

            返回一个迭代器,它对每个迭代项应用函数,得到结果。

      why:不使用for循环,就能将序列中的数据m--映射到给定的处理函数中。快速的对一个序列进行各种操作

    numbers = [1, 3, 5, 7, 9]
    
    # 改写成2,4,6,8,10
    
    #普通做法
    new_num = []
    for x in numbers:
        new_num.append(x+1)
    
    print(new_num)
    
    # map版本
    def addone(x):
        return x+1
    
    print(list(map(addone, numbers)))
    
    # 其他应用 改写字符串
    str_list = ['lilei', 'hmm', 'de8ug']
    def change(s: str):
        return s.upper()
    
    print(list(map(change, str_list)))

    1.2 filter 过滤、筛选

      官方: Construct an iterator from those elements of iterable for which function returns true. 

          iterable may be either a sequence, a container which supports iteration, or an iterator.

          If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

          从可迭代的元素中构造一个迭代器,函数返回true。iterable可以是一个序列,一个支持迭代的容器,

          或者一个迭代器。如果函数为None,则假定标识函数为false,即为 false的所有元素都被删除。

      why:不用for循环, 就能将序列中的数据一一映射到给定 的处理函数, 函数中添加了真假判断,

         True则返回 相应数据,最终得到筛选后的序列。

    '''
        查找大于30 小于50的数字列表
    '''
    my_list = [24,23,75,12,43,9,42,28,37]
    # 普通版本
    new_list = []
    
    for i in my_list:
        if 30 < i < 50:
            new_list.append(i)
    print(new_list)
    
    # filter版本
    def choose(x):
        # if 30 < i < 50:
        #     return True
        return 30 < x < 50  # < 操作的结果,已经是bool 类型了
    
    print(list(filter(choose, my_list)))
            
    # 字符串操作
    import re
    str_list = ['lilei', 'hmm', 'de8ug', 'debug1', 'de8ug2']
    
    def lh(s: str):
        return re.search('de8ug', s)
    
    print(list(filter(lh, str_list)))

    1.3 reduce 减少,合并

      官方:Apply function of two arguments cumulatively to the items of sequence, from left to right,

         so as to reduce the sequence to a single value.

         将两个参数的函数累积到序列的项上,从左到右,以便将序列减少到单个值。

       why: 为了快速的进行累加,连乘的计算 使代码更简洁

      需要注意:py3中吧reduce放到了fuctiontools这个模块下了

    from functools import reduce
    
    numbers = [1, 3, 5, 7, 9]
    
    # 普通版本 累加
    count = 0
    for i in numbers:
        count += i
    print(count)
    
    # reduce版 累加
    def add(x, y):
        return x+y
    
    print(reduce(add, numbers))
    
    # 普通版本 连乘
    count = 1
    for i in numbers:
        count *= i
    print(count)
    
    # reduce版本 连乘
    def mul(x, y):
        return x*y
    print(reduce(mul, numbers))

    二、 lambda表达式

    2.1  基本知识概览

     2.2 代码部分"1. 单参数 和 判断"

    f = lambda x: x*2
    f(2) # 4
    
    f = lambda x: True if x>8 else False
    print(f(9)) # True
    
    "2. 多参数"
    x = lambda x,y: x*y+2
    print(x(2,3)) # 8
    
    "3. 排序"
    users = [('de8ug', 18, 1), ('lilei', 20, 2), ('hmm', 17, 3), ('zhangsan', 30, 4)]
    users.sort(key=lambda x: x[1]) # x代表字典,每一个数组,要对谁排序,直接加上该位置
    users.sort(key=lambda x:(x[1],x[2])) . # 双排序
    print(users) "4. 字典的默认值" from collections import defaultdict # 生成默认的数值 d = defaultdict(lambda :0) d[1] print(d) # defaultdict(<function <lambda> at 0x101ab9950>, {1: 0}) # 生成默认的字符串 d = defaultdict(lambda :'abc') d[1] print(d) # defaultdict(<function <lambda> at 0x101ab9950>, {1: 'abc'}) # 生成二元数组,给地理信息使用 point = defaultdict(lambda :(2,3)) point['p1'] print(point) # defaultdict(<function <lambda> at 0x105a89950>, {'p1': (2, 3)}) "5. 在map,reduce,filter中使用,可以减少函数的定义" # 代码省略,看上面部分的代码

      

  • 相关阅读:
    《Python机器学习及实践:从零开始通往Kaggle竞赛之路》
    CPA专业阶段单科成绩有5年有效期限,即从通过科目考试的第一年算起
    升级gitk后,Error in startup script: unknown color name "lime"
    新三板:精选反馈问题103题(建议收藏)
    jQuery .on
    onload in JavaScript
    The JavaScript this Keyword
    JavaScript method overload
    JavaScript modularity with RequireJS (from spaghetti code to ravioli code)
    Understanding RequireJS for Effective JavaScript Module Loading
  • 原文地址:https://www.cnblogs.com/louhui/p/9165063.html
Copyright © 2020-2023  润新知