减少 - Python

Reduce - Python

我正在努力思考以下代码。我是否正确地推断 a 映射到 (a+x) 并且 x 是一个迭代器,随后迭代集合中的每个元素? (例如,最初是零,然后是 1,然后是 2)?

非常感谢任何指点!

sum = reduce(lambda a, x: a + x, [0, 1, 2, 3, 4])
print sum #10

是的,你是对的。

只是一个小的更正:a 不是 初始为零。它使用集合的第一个元素进行初始化。所以迭代从第二个元素开始。

来自documentation

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).

因此在您的情况下 reduce(lambda a, x: a + x, [0, 1, 2, 3, 4]) 计算出 ((((0+1)+2)+3)+4),即 10

在 Python 中,reduce 将函数应用于列表的前 2 项,然后将相同的函数应用于列表中第 3 项的结果,然后将函数应用于结果和列表中的第 4 项等等。

你的情况:

 a = 0 + 1
 b = a + 2
 c = b + 3
 d = c + 4
 sum = d

这可能有助于想象它是如何工作的:

def my_reduce(func, iterable):
    iterator = iter(iterable)
    res = next(iterator)
    for arg in iterator:
        res = func(res, arg)
    return res

>>> my_reduce(lambda a, x: a + x, [0, 1, 2, 3, 4])
10

其实这里有两个概念reducelambda。您可以定义一个 "normal" 函数,而不是使用 lambda

def add(a, b):
    return a + b

现在,可能会更清楚一点:

>>> reduce(add, [0, 1, 2, 3, 4])
10