python: reduce函数

来源:互联网 发布:ubuntu 字体 编辑:程序博客网 时间:2024/06/04 22:53

API

reduce(function, sequence, starting_value)

顺序迭代。

可设置初始值。

实验代码

未设置 初始值

默认sequence[0] 作为 初始值

list = [2, 3, 4]f = lambda x, y : x * yassert reduce(f, list) == 2*3*4

设置了 初始值

list = [2, 3, 4]f = lambda x, y : x * yassert reduce(f, list, 10) == 10*2*3*4

寻找最大值

list = [10, 100, 70, 20]assert reduce(lambda a,b : a if a>b else b, list) == 100

也可以用python 自带的 max函数

list = [10, 100, 70, 20]assert reduce(max, list) == 100

等同于:

list = [10, 100, 70, 20]assert max(list) == 100

求平方和

list = [2, 3, 4]assert reduce(lambda x,y : x+y**2, list, 0) == 2**2 + 3**2 + 4**2


原创粉丝点击