您不能使用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.
'exec'在python2中不是函数,它是一个声明。你不能在'lambda'中使用语句。你真的需要一个'lambda'吗?你不能定义一个正常的功能吗? – SilentGhost
使用不同的编程语言从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