我无法理解下面的代码段:的Python解释降低
>>> lot = ((1, 2), (3, 4), (5,))
>>> reduce(lambda t1, t2: t1 + t2, lot)
(1, 2, 3, 4, 5)
如何精简函数产生的(1,2,3,4,5)的元组?
我无法理解下面的代码段:的Python解释降低
>>> lot = ((1, 2), (3, 4), (5,))
>>> reduce(lambda t1, t2: t1 + t2, lot)
(1, 2, 3, 4, 5)
如何精简函数产生的(1,2,3,4,5)的元组?
,如果你打出来的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)
减少(...) 减少(函数,序列[,初始]) - >值
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, 2)+(3,4)
结果=结果+(5,)
请注意,您的减少连接元组。
减少需要的功能和迭代器作为参数。该函数必须接受两个参数。
减少的是它遍历迭代器。首先它将前两个值发送给函数。然后它将结果与下一个值一起发送,依此类推。
所以在你的情况下,它将元组1,2和3,4中的第一个和第二个项目发送到lambda函数。该功能将它们加在一起。结果与第三项一起再次发送到lambda函数。由于元组中没有更多项目,所以返回结果。
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
)。
重点是元组上的'+'是串联(不是算术加法)! –
你知道'reduce()'函数提供的抽象概括吗?我不相信这是非常有洞察力的,试图了解减少的每一个特定用法 – phant0m
@ phant0m我明白reduce()函数提供了什么。但在这个特殊的例子中,我被'+'弄糊涂了,我认为这是算术加法。 – Sibi