2012-11-12 104 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社區中多次討論過,但結論是,如果需要的話,它通常會更好和更少錯誤地顯式定義函數。

相關問題