用python编写函数 [英] Composing functions in python

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

问题描述

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

  def compose(list):如果len(list)== 1,则

return lambda x:list [0](x)
list.reverse()
final = lambda x:x
for list中的f:
final = lambda x:f(final(x))
返回最终

此方法



(我正在反转列表,因为这是我想要功能的组成顺序)

解决方案

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

作为快速解决方案,您可以将任务替换为:

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

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

  def wrap(accum,f):
返回lambda x: f(累计(x))
...
鳍al = wrap(final,f)

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

 >> l = [λ:在xrange(10)中n为n] 
>> [f in l中的f()]
[9、9、9、9、9、9、9、9、9、9]

此结果使许多人感到惊讶,他们期望结果为 [0,1,2,...] 。但是,所有的lambda都指向同一个 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天全站免登陆