zoukankan      html  css  js  c++  java
  • python 函数式编程

    lambda, map, filter, reduce

    lambda 匿名函数

    b = lambda a : a + 10
    

    map

    • map(f, iterator) 将f作用于iterator, 返回可迭代对象.
    • 列表生成式 [f(x) for x in iterator]
    num_list = list(range(10))
    list(map(lambda a : a + 10, num_list))
    

    filter

    • filter(condition_f, iterator) 过滤列表中满足条件的值, 返回可迭代对象.
    • 列表生成式 [x for x in iterator if condition]
    num_list = list(range(10))
    list(filter(lambda a : a > 5, num_list))
    

    列表生成式, map, filter 复杂度

    列表生成式在内存中保存所有结果, 耗内存; map, filter只在需要时调用(没有深究,需要时补)

    reduce

    • reduce(f, iterator[, init_value]) 滚动计算列表顺序对
    from functools import reduce
    
    num_list = list(range(5))
    reduce(lambda a, b: a + b, num_list)# return 10
    

    iterator

    iter

    • iter(data_structure)

    next

    • next(iterator) 返回下一个值, 返回最后一个值后再调用,返回异常

    装饰器

    应用:

    1. 输出函数的参数
    2. 缓存函数返回值
    3. 处理管理逻辑(路由,权限等)

    函数中返回函数:

    # Our first decorator
    def debug(function):
        def modified_function(*args, **kwargs):
            print("Arguments:", args, kwargs)
            return function(*args, **kwargs)
        return modified_function
    

    装饰器:

    @debug
    def foo(a, b, c=1):
        return (a + b) * c
    
    #foo = debug(foo)
    foo(1,1,3)
    
    -------------------------------------------------------------逆水行舟,不进则退。
  • 相关阅读:
    梦断代码读后感一
    二阶段之五
    二柱子阶段二
    动手动脑
    二柱子
    开学测试
    jdk的安装
    软工人8月30日学习记录
    软工人8月29日学习记录
    软工人8月28日学习记录
  • 原文地址:https://www.cnblogs.com/alilliam/p/12460949.html
Copyright © 2011-2022 走看看