Sib*_*ibi 4 python reduce functional-programming
我无法理解以下代码段:
>>> lot = ((1, 2), (3, 4), (5,))
>>> reduce(lambda t1, t2: t1 + t2, lot)
(1, 2, 3, 4, 5)
Run Code Online (Sandbox Code Playgroud)
reduce函数如何产生(1,2,3,4,5)元组?
Jon*_*nts 13
如果你突破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)
Run Code Online (Sandbox Code Playgroud)
reduce()按顺序应用函数,链接序列的元素:
reduce(f, [a,b,c,d], s)
Run Code Online (Sandbox Code Playgroud)
是相同的
f(f(f(f(s, a), b), c), d)
Run Code Online (Sandbox Code Playgroud)
等等。在你的例子中,它f()是一个 lambda 函数(lambda t1, t2: t1 + t2),它只是将两个参数相加,所以你最终得到
(((s + a) + b) + c) + d
Run Code Online (Sandbox Code Playgroud)
因为添加序列时的括号没有任何区别,所以这是
s + a + b + c + d
Run Code Online (Sandbox Code Playgroud)
或与您的实际值
(1, 2) + (3, 4) + (5,)
Run Code Online (Sandbox Code Playgroud)
如果s没有给出,第一项就没有完成,但通常中性元素用于s,所以在你的情况下()是正确的:
reduce(lambda t1, t2: t1 + t2, lot, ())
Run Code Online (Sandbox Code Playgroud)
lot但如果没有它,只有在没有元素 ( )时才会遇到麻烦TypeError: reduce() of empty sequence with no initial value。