Python 官方文档:入门教程 => 点击学习
目录1 reduce用法2 reduce与for循环性能对比reduce函数原本在python2中也是个内置函数,不过在python3中被移到functools模块中。 reduce
reduce函数原本在python2中也是个内置函数,不过在python3中被移到functools模块中。
reduce函数先从列表(或序列)中取出2个元素执行指定函数,并将输出结果与第3个元素传入函数,输出结果再与第4个元素传入函数,…,以此类推,直到列表每个元素都取完。
对列表元素求和,如果不用reduce,我们一般常用的方法是for循环:
def sum_func(arr):
if len(arr) <= 0:
return 0
else:
out = arr[0]
for v in arr[1:]:
out += v
return out
a = [1, 2, 3, 4, 5]
print(sum_func(a))
可以看到,代码量比较多,不够优雅。如果使用reduce,那么代码将非常简洁:
from functools import reduce
a = [1, 2, 3, 4, 5]
def add(x, y): return x + y
print(reduce(add, a))
输出结果为:
15
与内置函数map和filter不一样的是,在性能方面,reduce相比较for循环来说没有优势,甚至在实际测试中
reduce比for循环更慢。
from functools import reduce
import time
def test_for(arr):
if len(arr) <= 0:
return 0
out = arr[0]
for i in arr[1:]:
out += i
return out
def test_reduce(arr):
out = reduce(lambda x, y: x + y, arr)
return out
a = [i for i in range(100000)]
t1 = time.perf_counter()
test_for(a)
t2 = time.perf_counter()
test_reduce(a)
t3 = time.perf_counter()
print('for循环耗时:', (t2 - t1))
print('reduce耗时:', (t3 - t2))
输出结果如下:
for循环耗时: 0.009323899999999996
reduce耗时: 0.018477400000000005
因此,如果对性能要求苛刻,建议不用reduce, 如果希望代码更优雅而不在意耗时,可以用reduce。
到此这篇关于Python中reduce函数详解的文章就介绍到这了,更多相关Python reduce函数内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Python中reduce函数详解
本文链接: https://www.lsjlt.com/news/118672.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0