2012-11-12 102 views
0

我正在阅读Structure and Interpretation of Computer Programs - 在计算机科学领域享有盛誉。我可以在多行的python中编写lambda函数,并调用其他函数吗?

在函数式编程的鼓励下,我尝试用Python代码而不是Scheme,因为我觉得它更易于使用。但后来出现这样的问题:我需要多次Lambda函数,但我无法弄清楚如何使用lambda编写一个复杂操作的未命名函数。

在这里,我想写一个lambda函数,其字符串变量为exp作为它的唯一参数并执行exec(exp)。但我得到一个错误:

>>> t = lambda exp : exec(exp) 
File "<stdin>", line 1 
t = lambda exp : exec(exp) 
        ^
SyntaxError: invalid syntax 

它是如何发生的?如何应对呢?

我阅读了我的Python指导手册,并在没有找到我想要的答案的情况下搜索Google。这是否意味着python中的lambda函数只能用于语法糖?

+3

'exec'在python2中不是函数,它是一个声明。你不能在'lambda'中使用语句。你真的需要一个'lambda'吗?你不能定义一个正常的功能吗? – SilentGhost

+1

使用不同的编程语言从SICP等非平凡的教科书中学习是一个好主意,在那个你不完全熟悉的教科书中学习。在你解决这个问题后,你肯定会遇到其他的问题,例如[关闭中的任务](http://stackoverflow.com/questions/7535857/why-doesnt-this-closure-modify-the-variable-在封闭作用域中)或者[使用循环创建闭包](http://stackoverflow.com/questions/233673/lexical-closures-in-python)。 Python是一门伟大的语言,但它不是Scheme的简单替代品。 – user4815162342

回答

7

您不能使用lambda正文中的声明,这就是为什么您会收到该错误,lambda只能预期表达式。

但是在Python 3 exec是一个功能和在那里工作罚款:

>>> t = lambda x: exec(x) 
>>> t("print('hello')") 
hello 

在Python 2,你可以使用compile()eval()

>>> t = lambda x: eval(compile(x, 'None','single')) 
>>> strs = "print 'hello'" 
>>> t(strs) 
hello 

帮助上compile()

compile(...) 
    compile(source, filename, mode[, flags[, dont_inherit]]) -> code object 

    Compile the source string (a Python module, statement or expression) 
    into a code object that can be executed by the exec statement or eval(). 
    The filename will be used for run-time error messages. 
    The mode must be 'exec' to compile a module, 'single' to compile a 
    single (interactive) statement, or 'eval' to compile an expression. 
    The flags argument, if present, controls which future statements influence 
    the compilation of the code. 
    The dont_inherit argument, if non-zero, stops the compilation inheriting 
    the effects of any future statements in effect in the code calling 
    compile; if absent or zero these statements do influence the compilation, 
    in addition to any features explicitly specified. 
+0

谢谢!!这正是我需要的。 – Edward

0

lambda语句(不是函数)只能是一行,并且只能包含一个表达式。表达式可以包含函数调用,例如lambda: my_func()。然而,exec是一个声明,而不是函数,因此不能用作表达式的一部分。

多行lambdas的问题已经在python社区中多次讨论过,但结论是,如果需要的话,它通常会更好和更少错误地显式定义函数。

相关问题