2012-11-28 36 views
3

我無法理解下面的代碼段:的Python解釋降低

>>> lot = ((1, 2), (3, 4), (5,)) 
>>> reduce(lambda t1, t2: t1 + t2, lot) 
(1, 2, 3, 4, 5) 

如何精簡函數產生的(1,2,3,4,5)的元組?

+5

重點是元組上的'+'是串聯(不是算術加法)! –

+0

你知道'reduce()'函數提供的抽象概括嗎?我不相信這是非常有洞察力的,試圖瞭解減少的每一個特定用法 – phant0m

+0

@ phant0m我明白reduce()函數提供了什麼。但在這個特殊的例子中,我被'+'弄糊塗了,我認爲這是算術加法。 – Sibi

回答

11

,如果你打出來的lambda成一個函數它更容易,所以它更清楚這是怎麼回事:

>>> def do_and_print(t1, t2): 
    print 't1 is', t1 
    print 't2 is', t2 
    return t1+t2 

>>> reduce(do_and_print, ((1,2), (3,4), (5,))) 
t1 is (1, 2) 
t2 is (3, 4) 
t1 is (1, 2, 3, 4) 
t2 is (5,) 
(1, 2, 3, 4, 5) 
1

減少(...) 減少(函數,序列[,初始]) - >值

Apply a function of two arguments cumulatively to the items of a sequence, 
from left to right, so as to reduce the sequence to a single value. 
For example, reduce(lambda x, y: x+y, ((1, 2), (3, 4), (5))) calculates 
(((1+2)+(3+4))+5). If initial is present, it is placed before the items 
of the sequence in the calculation, and serves as a default when the 
sequence is empty. 
1

讓我們跟蹤減少

結果=(1, 2)+(3,4)

結果=結果+(5,)

請注意,您的減少連接元組。

0

減少需要的功能和迭代器作爲參數。該函數必須接受兩個參數。

減少的是它遍歷迭代器。首先它將前兩個值發送給函數。然後它將結果與下一個值一起發送,依此類推。

所以在你的情況下,它將元組1,2和3,4中的第一個和第二個項目發送到lambda函數。該功能將它們加在一起。結果與第三項一起再次發送到lambda函數。由於元組中沒有更多項目,所以返回結果。

3

reduce()施加順序的函數,鏈接序列中的元素:

reduce(f, [a,b,c,d], s) 

相同

f(f(f(f(s, a), b), c), d) 

等。在你的情況f()是一個lambda函數(lambda t1, t2: t1 + t2)剛剛增加了兩個參數,所以你最終

(((s + a) + b) + c) + d 

而且由於添加序列圓括號沒有什麼差別,這是

s + a + b + c + d 

或與您的實際值

(1, 2) + (3, 4) + (5,) 

如果s沒有給出,第一項只是沒有這樣做,但通常ŧ他中性元素用於s,所以你的情況()本來是正確的:

reduce(lambda t1, t2: t1 + t2, lot,()) 

但是,如果沒有它,你只遇到麻煩,如果lot沒有任何元素(TypeError: reduce() of empty sequence with no initial value)。