函数使用 reduce, map, filter, compose

reduce 用法

reduce(func, seq) 等同于func(func(seq[0], seq[1]),seq[2]),…

from functools import reduce
reduce(lambda x, y: x+y, [1,2,3,4,5]) # 使用 lambda 匿名函数15
15

map 用法

map(func, seq) 对序列中的每个元素应用func

from functools import reduce
list(map(lambda x: x*2, [1,2,3,4,5])) 
[2, 4, 6, 8, 10]

filter 用法

filter(func, seq) 返回函数为真的元素的列表

#from functools import filter
list(filter(lambda x: x >2, [1,2,3,4,5]))
[3, 4, 5]

compose 多层函数套用

参考链接: https://mathieularose.com/function-composition-in-python/

使用1, 习惯函数套用

def compose2(f, g):
    return lambda x: f(g(x))
def double(x):
    return x * 2
def inc(x):
    return x + 1
def dec(x):
    return x-1
inc_and_double = compose2(double, inc)
print(inc_and_double(10)) #22
inc_double_and_dec = compose2(compose2(dec, double), inc)
print(inc_double_and_dec(10)) #21
22
21

使用2

import functools
def compose(*functions):
    def compose2(f, g):
        return lambda x: f(g(x))
    return functools.reduce(compose2, functions, lambda x: x)
inc_double_and_dec = compose(dec, double, inc)
print(inc_double_and_dec(10))  #21
21

使用3

import functools
def compose(*functions):
    return functools.reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)
inc_double_and_dec = compose(dec, double, inc)
print(inc_double_and_dec(10))  #21


21

使用4

def compose(*funcs):
    """Compose arbitrarily many functions, evaluated left to right.

    Reference: https://mathieularose.com/function-composition-in-python/
    """
    # return lambda x: reduce(lambda v, f: f(v), funcs, x)
    if funcs:
        return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs)
    else:
        raise ValueError('Composition of empty sequence not supported.')
def incXY(*args,**kwargs):
    sum_a = 0
    for i in args:
        sum_a += i
    for i, j in kwargs.items():
        sum_a +=j
    return sum_a
def decXY(*args,**kwargs):
    sum_a = 0
    for i in args:
        sum_a += i
    for i, j in kwargs.items():
        sum_a -=j
    return sum_a
XY_inc_dec = compose(incXY,decXY)
print(XY_inc_dec(10,11,pintput=5))
26
发布了36 篇原创文章 · 获赞 0 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_38102912/article/details/100670662