Python基础之reduce函数

哈喽大家好,今天说一下reduce函数的使用方法,以及与for循环的对比。

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

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

在学习过程中,由于没有好的教材和教程,学习方向不明确,遇到的问题没有及时解决,失去了学习的兴趣和动力,不仅浪费时间和精力。下一次我想学点东西,但我对它不感兴趣。<details><summary>*<font color='gray'>[En]</font>*</summary>*<font color='gray'>In the process of learning, because there are no good materials and tutorials, the learning direction is not clear, and the problems encountered are not solved in time, they lose their interest and motivation in learning, which is not only a waste of time and energy. and next time I want to learn something, but I'm not interested in it.</font>*</details>

所以小编创了一个学习交流q君羊 279199867,准备了海量的学习资料,直接找管理领取就可以了,同数千志同道合的人一同学习交流,

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

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。

好了,今天的分享就到这里。如果对你有帮助,你可以留着。

[En]

Well, that’s all for today’s sharing. You can keep it if it’s helpful to you.

给大家推荐一套Python爬虫教程,涵盖了大部分的常见案例,非常好用!

Python 爬虫实战一百例

Original: https://www.cnblogs.com/hahaa/p/16602338.html
Author: 轻松学Python
Title: Python基础之reduce函数

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/498709/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球