我可以在多行的python中编写lambda函数,并调用其他函数吗?

0 python

我正在阅读计算机程序的结构和解释 - 在计算机科学领域很有名.

受到函数式编程的鼓励,我尝试用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
Run Code Online (Sandbox Code Playgroud)

怎么会发生?如何应对呢?

我阅读了我的Python指南,并在没有找到我想要的答案的情况下搜索了Google.这是否意味着lambdapython 中的函数只是设计为语法糖?

Ash*_*ary 7

你不能在lambdabody中使用一个语句,这就是你得到那个错误的原因,lambda只需要表达式.

但在Python 3中exec是一个功能,并在那里工作正常:

>>> t = lambda x: exec(x)
>>> t("print('hello')")
hello
Run Code Online (Sandbox Code Playgroud)

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

>>> t = lambda x: eval(compile(x, 'None','single'))
>>> strs = "print 'hello'"
>>> t(strs)
hello
Run Code Online (Sandbox Code Playgroud)

帮助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.
Run Code Online (Sandbox Code Playgroud)