lambda如何与reduce一起工作 [英] how lambda works with reduce

查看:69
本文介绍了lambda如何与reduce一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解reduce如何通过该网站工作.他们提到的示例非常好,而且易于理解.

I was trying to understand how reduce works through this website. The example they have mentioned is quite good and easy to understand.

http://book.pythontips.com/en/latest/map_filter .html#reduce

a = reduce((lambda x, y: x * y), [1, 2, 3, 4])

以上功能将列表中的每个数字倍增并分配给a.

The above function will multiple each and every number in list and assign to a.

但是,当我在项目中遇到以下功能时,我感到非常沮丧.

However, I got totally stumped when I came across following function in project.

def compose(*fns):
    return reduce(lambda acc, fn: lambda *args: acc(fn(*args)), fns, lambda _: _)

有人可以帮助我分解此功能以了解应该做什么

could someone help me breakdown this function to understand what it's suppose to do

推荐答案

lambda表达式可能很难遵循,尤其是在使用此表达式时,它返回了一个新函数,该函数也使用lambda定义.

lambda expressions can be difficult to follow, and especially so with this one, which returns a new function, also defined using lambda.

这里是相同的表达式,但行距不同:

Here is that same expression, but with some different line spacing:

def compose(*fns):
    return reduce(lambda acc, fn: lambda *args: acc(fn(*args)), 
                  fns,
                  lambda _: _)

现在,我将通过分解作为常规def语句传递给reducelambda来进一步扩展此功能:

Now I'll further expand this by exploding the lambdas passed to reduce as a regular def statements:

def compose_2_fns(f, g):
    # take 2 functions and return a new function that calls the first with the
    # result of calling the second
    def composed(*args):
        return f(g(*args))
    return composed

def _initial(x):
    return x

def compose(*fns):
    return reduce(compose_2_fns, fns, _initial)

回想一下reduce的工作原理是为它提供一个带有2个参数的方法,一个对象序列(在这种情况下,是一个函数序列)和一个可选的初始值.

Recall that reduce works by giving it a method that takes 2 arguments, a sequence of objects (in this case, a sequence of functions), and an optional initial value.

reduce(reduce_fn, objs, first_obj)

如果未提供初始值,则reduce将采用序列中的第一个对象,就像您按如下方式调用它一样:

If no initial value is given, reduce will take the first object in the sequence, as if you had called it like:

reduce(reduce_fn, objs[1:], objs[0])

然后将reduce函数这样调用:

Then the reduce function is called like this:

accumulator = first_obj
for obj in objs:
    accumulator = reduce_fn(accumulator, obj)
return accumulator

所以您发布的reduce语句正在做的事情是通过组合几个较小的函数来构建一个大函数.

So what your posted reduce statement is doing is building up a big function by combining several smaller ones.

functions = (add_1, mult_5, add_3)
resulting_function -> lambda *args: add_1(mult_5(add_3(*args)))

因此:

resulting_function(2) -> (((2 + 3) * 5) + 1) -> 26

这篇关于lambda如何与reduce一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆