Python中reduce函数详解

作者:走召大爷 时间:2022-09-03 12:26:33 

reduce函数原本在python2中也是个内置函数,不过在python3中被移到functools模块中。

reduce函数先从列表(或序列)中取出2个元素执行指定函数,并将输出结果与第3个元素传入函数,输出结果再与第4个元素传入函数,…,以此类推,直到列表每个元素都取完。

1 reduce用法

对列表元素求和,如果不用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

2 reduce与for循环性能对比

与内置函数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。

来源:https://blog.csdn.net/huachao1001/article/details/124060003

标签:Python,reduce函数
0
投稿

猜你喜欢

  • PHP simplexml_load_string()函数实例讲解

    2023-07-09 07:19:28
  • Python之ascii转中文的实现

    2023-08-24 19:39:12
  • JavaScript的陷阱

    2008-10-28 19:52:00
  • Go语言HTTPServer开发的六种方式小结

    2023-06-22 21:48:21
  • Oracle 创建监控账户 提高工作效率

    2009-10-14 11:47:00
  • 淘宝CSS框架研究(1):Reset CSS(八卦篇)

    2009-03-31 12:58:00
  • python-序列解包(对可迭代元素的快速取值方法)

    2023-12-28 23:23:57
  • Python基于pillow判断图片完整性的方法

    2021-05-12 21:55:50
  • python实现拓扑排序的基本教程

    2021-03-24 04:24:02
  • 轻松掌握python设计模式之访问者模式

    2023-06-30 13:46:39
  • Python利用flask sqlalchemy实现分页效果

    2023-10-05 16:36:21
  • 间歇向上无缝翻滚代码

    2008-05-05 12:30:00
  • Python下划线5种含义代码实例解析

    2023-11-19 04:25:59
  • Python实现统计文本文件字数的方法

    2023-05-24 11:46:04
  • 利用Python实现Windows下的鼠标键盘模拟的实例代码

    2023-06-22 04:37:31
  • python中Pyqt5使用Qlabel标签进行视频播放

    2021-12-19 13:32:20
  • 文字的减法

    2007-11-06 12:58:00
  • python 迭代器和iter()函数详解及实例

    2022-03-24 17:55:33
  • 对json字符串与python字符串的不同之处详解

    2023-11-22 04:35:39
  • linux下mysql命令

    2011-01-04 19:42:00
  • asp之家 网络编程 m.aspxhome.com