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)
posted @ 2020-03-11 10:50  youqia  阅读(151)  评论(0编辑  收藏  举报