我无法理解以下代码片段:
>>> lot = ((1, 2), (3, 4), (5,))
>>> reduce(lambda t1, t2: t1 + t2, lot)
(1, 2, 3, 4, 5)
reduce函数如何生成元组(1,2,3,4,5)?
我无法理解以下代码片段:
>>> lot = ((1, 2), (3, 4), (5,))
>>> reduce(lambda t1, t2: t1 + t2, lot)
(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)
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(...) reduce(function, sequence[, initial]) -> value
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.
让我们来追踪这个reduce
result = (1,2) + (3,4)
result = result + (5, )
请注意,您的缩减将元组连接在一起。
reduce函数接受一个函数和一个迭代器作为参数。该函数必须接受两个参数。
reduce的作用是遍历可迭代对象。首先将前两个值发送到函数中,然后将其结果与下一个值一起发送,以此类推。
因此,在您的情况下,它将获取元组中的第一个和第二个项目(1,2)和(3,4),并将它们发送到lambda函数中。该函数将它们相加。结果再次发送到lambda函数中,与第三个项目一起。由于元组中没有更多的项目,因此返回结果。
+
表示连接(而不是数学加法)! - Andrew Jaffereduce()
函数提供的抽象概念吗?我认为试图理解 reduce 的每个特定用法并不是很有洞见。 - phant0m