Function uses reduce, map, filter, compose

reduce usage

reduce (func, seq) is equivalent to 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 Usage

map (func, seq) func application of each element of the sequence

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

filter usage

filter (func, seq) function returns true element of the list

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

compose a multi-layer functions apply

Reference Links: https://mathieularose.com/function-composition-in-python/

Use 1, used to apply the function

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

Use 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

Use 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

Use 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
Published 36 original articles · won praise 0 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_38102912/article/details/100670662