zoukankan      html  css  js  c++  java
  • python高级特性和高阶函数

    python高级特性

    1、集合的推导式

    • 列表推导式,使用一句表达式构造一个新列表,可包含过滤、转换等操作。

    语法:[exp for item in collection if codition]

    if codition - 可选

    • 字典推导式,使用一句表达式构造一个新列表,可包含过滤、转换等操作。

    语法:{key_exp:value_exp for item in collection if codition}

     

    • 集合推导式

    语法:{exp for item in collection if codition}

    • 嵌套列表推导式

     

    2、多函数模式

    函数列表,python中一切皆对象。

    # 处理字符串
    str_lst = ['$1.123', '  $1123.454', '$899.12312']
    
    def remove_space(str):
        """
        remove space
        """
        str_no_space = str.replace(' ', '')
        return str_no_space
    
    def remove_dollar(str):
        """
        remove $
        """
        if '$' in str:
            return str.replace('$', '')
        else:
            return str
    
    def clean_str_lst(str_lst, operations):
        """
            clean string list
        """
        result = []
        for item in str_lst:
            for op in operations:
                item = op(item)
            result.append(item)
        return result
    
    clean_operations = [remove_space, remove_dollar]
    result = clean_str_lst(str_lst, clean_operations)
    print result
    

    执行结果:['1.123', '1123.454', '899.12312']

     

    3、匿名函数lambda

    • 没有函数名
    • 单条语句组成
    • 语句执行的结果就是返回值
    • 可用作sort的key函数

     

    python高阶函数

    1、函数式编程

    • 函数本身可以赋值给变量,赋值后变量为函数;
    • 允许将函数本身作为参数传入另一个函数;
    • 允许返回一个函数。

    2、map/reduce函数

    • map(fun, lst),将传入的函数变量func作用到lst变量的每个元素中,并将结果组成新的列表返回

    • reduce(func(x,y),lst),其中func必须有两个参数。每次func计算的结果继续和序列的下一个元素做累积计算。

      lst = [a1, a2 ,a3, ......, an]

      reduce(func(x,y), lst) = func(func(func(a1, a2), a3), ......, an)

    3、filter函数

    • 筛选序列
    • filter(func, lst),将func作用于lst的每个元素,然后根据返回值是True或False判断是保留还是丢弃该元素。

  • 相关阅读:
    ADB 操作手机的粘贴板
    JSESSIONID的简单说明
    Android无线调试出现错误的解决方法
    adb shell input text 完美支持中文输入
    SQL Server 2022来了
    新技能GET!在前端表格中花式使用异步函数的奥义
    地表最强IDE ——Visual Studio 2022正式发布
    用前端表格技术构建医疗SaaS 解决方案
    JavaScript Sanitizer API:原生WEB安全API出现啦
    突破技术限制,实现Web端静默打印
  • 原文地址:https://www.cnblogs.com/shhnwangjian/p/6533317.html
Copyright © 2011-2022 走看看