zoukankan      html  css  js  c++  java
  • Python函数式编程,map/reduce,filter和sorted

    什么是函数式编程?

    • 与面向对象编程(Object-oriented programming)和过程式编程(Procedural programming)并列的编程范式。
    • 最主要的特征是,函数是第一等公民,可以定义在函数内外,作为函数参数或返回值,函数的组合。
    • 强调将计算过程分解成可复用的函数,典型例子就是map方法和reduce方法组合而成 MapReduce 算法
    • 只有纯的、没有副作用的函数,才是合格的函数。  

    知乎-什么是函数式编程思维?

    函数式编程与命令式编程最大的不同其实在于:

    函数式编程关心数据的映射,命令式编程关心解决问题的步骤。

    所以函数式编程最重要的是数据的映射,要用数学的思维去解决问题,而不是计算机指令。

     

    map/reduce

    map()函数接受一个函数,一个或多个可迭代对象,函数作用于迭代对象的每一个元素上并以迭代器返回。

    def abs(x):
            if x > 0:
                     return x
            return -x
    #map()返回迭代器,惰性,需要list转化一下 a
    = list(map(abs,[-1,-6,7,10])) >>>a [1,6,7,10]


    ####求两个list元素的对应乘积返回list
     def sub(x,y):
          
    return x * y
    a
    = list(map(sub,[1,2,3],[4,5,6]))
    >>>a
    [
    4,10,18]
     


     

    reduce

    Python3已经将reduce()从全局移除,要使用需要从函数与工具导入

    >>>from functools import reduce

    reduce函数接受的函数必须有两个参数,另一个为list或tuple

    从元素开始取两个元素做积累运算

    from funtools import reduce
    def add(x,y):
        return x + y
    
    a = reduce(add,[1,2,3,4,5])
    >>>a
    15

    还可以将list或者tuple转化为整数

    from functools import reduce
    
    def tra(x,y):
        return x*10 + y
    
    a = reduce(tra,(1,2,3,4,5))
    >>>a
    12345

    map()和reduce()配合使用

    from functools import reduce
    
    def sq(x):
        return x * x 
    
    def add(y,z):
        return y + z
    
    a = reduce(add,map(sq,[1,2,3]))
    >>>a
    14

     

    filter过滤器

    filter()接受一个函数,一个序列,函数依次作用在每个元素上,保留Ture丢弃FALSE

    ###只保留正数
    def
    filt(x): if x > 0: return x #filter返回迭代器,惰性,需要list转换一下 a = list(map(filt,[-1,-2,3,4])) >>>a [3,4]

     

    sorted

    sorted(iterable, key=None, reverse=False)

    sorted()函数也是一个高阶函数,key可以接受一个函数作用在每个元素上返回

    sorted([2,4,1,3,7])
    [1,2,3,4,7]
    
    #key接受函数
    
    >>>sorted([1,-5,3,-6],key=abs)
    [-6,-5,1,3]

    #可以传入第三参数reverse=Ture,默认正序为FALSE实现倒序排序
    >>>sorted([1,3,5,7,9]reverse=Ture)
    [9,7,5,3,1]

    ######sort函数
    a = [1,0,3,5,4]
    a.sort()
    >>>print(a)
    [0,1,3,4,5]
    #倒序
    a = [1,0,3,5,4]
    a.sort(reverse = True)
    >>>print(a)
    [5,4,3,1,0]
    如果需要一个list副本,不要使用赋值方法,这样得到的副本还是原来的list,在内存中指向同一个地址
    要使用切片操作,才能得到新的副本
  • 相关阅读:
    根据坐标经纬度计算两点之间的距离
    C# 获取类名
    Post、Get请求
    Image和Base64相互转换
    Html checkbox全选
    .NET Core 中间件
    C# DataTable 用法
    imshow(A,[])和imshow(A)的区别
    Log-spectral distance
    CUDA
  • 原文地址:https://www.cnblogs.com/mzc1997/p/7613054.html
Copyright © 2011-2022 走看看