在python中组合函数 [英] Composing functions in python

查看:40
本文介绍了在python中组合函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数数组,我正在尝试生成一个函数,该函数由数组中元素的组合组成.我的方法是:

def compose(list):如果 len(list) == 1:返回 lambda x:list[0](x)list.reverse()最终=拉姆达x:x对于列表中的 f:最终=拉姆达x:f(最终(x))返回决赛

此方法似乎不起作用,将不胜感激.

(我正在颠倒列表,因为这是我希望函数的组合顺序)

解决方案

它不起作用,因为您在循环中创建的所有匿名函数都引用同一个循环变量,因此共享其最终值.

作为快速修复,您可以将分配替换为:

final = lambda x, f=f, final=final: f(final(x))

或者,您可以从函数返回 lambda:

def wrap(accum, f):返回 lambda x: f(accum(x))...final = wrap(final, f)

要了解发生了什么,请尝试以下实验:

<预><代码>>>>l = [lambda: n for n in xrange(10)]>>>[f() for f in l][9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

这个结果让很多人感到惊讶,他们预计结果是 [0, 1, 2, ...].然而,所有的 lambdas 都指向同一个 n 变量,并且都指向它的最终值,即 9.在你的情况下,所有的 final 版本都被认为是嵌套最终引用相同的 f,更糟糕的是,引用相同的 final.

关于 Python 中的 lambda 和 for 循环的主题已经已经在 SO 上介绍.

I have an array of functions and I'm trying to produce one function which consists of the composition of the elements in my array. My approach is:

def compose(list):
    if len(list) == 1:
        return lambda x:list[0](x)
    list.reverse()
    final=lambda x:x
    for f in list:
        final=lambda x:f(final(x))
    return final

This method doesn't seems to be working, help will be appreciated.

(I'm reversing the list because this is the order of composition I want the functions to be)

解决方案

It doesn't work because all the anonymous functions you create in the loop refer to the same loop variable and therefore share its final value.

As a quick fix, you can replace the assignment with:

final = lambda x, f=f, final=final: f(final(x))

Or, you can return the lambda from a function:

def wrap(accum, f):
    return lambda x: f(accum(x))
...
final = wrap(final, f)

To understand what's going on, try this experiment:

>>> l = [lambda: n for n in xrange(10)]
>>> [f() for f in l]
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

This result surprises many people, who expect the result to be [0, 1, 2, ...]. However, all the lambdas point to the same n variable, and all refer to its final value, which is 9. In your case, all the versions of final which are supposed to nest end up referring to the same f and, even worse, to the same final.

The topic of lambdas and for loops in Python has been already covered on SO.

这篇关于在python中组合函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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