我只是在探索减少,但我不了解其背后的整个系统。我确实知道reduce很有可能会返回单个值,但是在这种情况下它如何工作?
answer = reduce(lambda x, y: x[0]*x[1] * ([y[0] + y[1]]), [(2,6), (1, 2), (5, 6)])
答案 0 :(得分:3)
[y[0] + y[1]]
是一个列表,因此您的lambda就是将一个整数x[0]*x[1]
与一个列表([y[0] + y[1]])
相乘,因此您将得到另一个列表,因为:
>>> 5 * [6]
[6, 6, 6, 6, 6]
>>> 8 * [4,6]
[4, 6, 4, 6, 4, 6, 4, 6, 4, 6, 4, 6, 4, 6, 4, 6]
关于为什么是9 * [11]
的原因:
>>> def thing(x, y):
... print(x, y)
... return x[0]*x[1] * ([y[0] + y[1]])
...
>>> reduce(thing, [(2,6), (1, 2), (5, 6)])
1. (2, 6) (1, 2)
2. [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] (5, 6)
[11, 11, 11, 11, 11, 11, 11, 11, 11]
x == (2, 6)
,y == (1, 2)
=> tmp1 == (2 * 6) * [1 + 2] == 12 * [3]
x
现在是前一次迭代中3的列表。根据您的公式,result == (3 * 3) * [5 + 6] == 9 * [11]