2011-12-30 68 views
2

可能重複:
What is a lambda and what is an example implementation?請解釋拉姆達運作

下面是一個lambda代碼(在Python的字節):

def make_repeater(n): 
    return lambda s: s * n 

twice = make_repeater(2) 

print twice('word') 
print twice(5) 

的輸出是這:

wordword 
10 

有人可以解釋lambda如何在longform中工作嗎? lambda函數中word5如何傳遞給s

謝謝。

+0

不錯的工作要求比「可能的重複」問題更好的問題,但第一個答案非常棒。 – sarnold 2011-12-30 23:44:56

+1

我想我會得到一個心理堆棧溢出錯誤從遞歸到重複的問題... – FakeRainBrigand 2011-12-30 23:47:35

+0

請參閱[理解-python中的lambda函數](http://stackoverflow.com/questions/17833228/understanding-lambda-功能?LQ = 1) – nawfal 2014-07-04 06:09:31

回答

4

正如Jake所述,您的make_repeater返回另一個函數, n被綁定到2(這被稱爲closure)。所以,你的代碼大致相當於:

twice = lambda s: s * 2 

print twice('word') 
print twice(5) 

這又大致相當於:

def twice(s): 
    return s * 2 

print twice('word') 
print twice(5) 

這又大致相當於:

print 'word' * 2 
print 5 * 2 

所以你實際上做是:

  • 評估表達式'word' * 2,這導致'wordword'
  • 計算表達式5 * 2,這導致10(這不應該你感到吃驚)

的(字符串乘法是通過Python作爲重複串中的給定次數定義)事實上你的lambda函數不關心它的參數類型,並且在運行時動態地決定乘法的哪個方法是正確的,被稱爲dynamic typing

1

函數make_repeater返回另一個函數(lambda)。在你的例子中,lambda函數被分配名稱「兩次」。 lambda具有一個參數「s」和一個「靜態」值「n」 - 在創建lambda時定義了「n」(在這種情況下,它被分配爲「2」)。當調用lambda時 - 「word」或5. word * 2 =「wordword」和5 * 2 = 10時,確定「s」的值。