Discuss / Python / 我研究了一下reduce(lambda acc, x: acc + x, ns)

我研究了一下reduce(lambda acc, x: acc + x, ns)

Topic source

雨鸢梦

#1 Created at ... [Delete] [Delete and Lock User]

看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:

>>> from functools import reduce>>> def add(x, y):
... return x + y
...>>> reduce(add, [1, 3, 5, 7, 9])
25

然后看一下lambda

a = lambda x:x+1
print(a(1))
#结果是2

def b(x):
    return x+1
print(b(1))
#结果也是2

上面两个函数其实是等价的

lambda作为一个表达式,定义了一个匿名函数,上例的代码x为入口参数,x+1为函数体

所以这里的reduce(lambda acc, x: acc + x, ns),其实可以等价于

def a(acc,x):        return acc+x    return reduce(a,ns)

  • 1

Reply