• reduce()函数


    在Python 3里,reduce()函数已经被从全局名字空间里移除了,它现在被放置在fucntools模块里
    用的话要 先引入
    from functools import reduce

    functools.reduce(function, iterable[, initializer])

    functools - Higher-order functions and operations on callable objects
    https://docs.python.org/3/library/functools.html

    functools - 高阶函数和可调用对象上的操作
    https://docs.python.org/zh-cn/3/library/functools.html

    Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.
    将两个参数的函数累加到序列项中,从左到右,以便将序列减少为单个值。例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 计算 ((((1+2)+3)+4)+5)。左参数 x 是累加值,右参数 y 是序列的更新值。如果存在可选的初始值设定项,则它将位于计算中序列的项之前,并在序列为空时用作默认值。如果未给出初始化程序且序列仅包含一个项目,则返回第一个项目。

    reduce() 函数会对参数序列中元素进行累积。

    函数将一个数据集合 (链表,元组等) 中的所有数据进行下列操作:用传给 reduce 中的函数 function (有两个参数) 先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

    function - 函数,有两个参数 (接收两个值作为输入,执行计算,然后返回一个值作为输出。)
    iterable - 可迭代对象
    initializer - 可选,初始参数

    Roughly equivalent to:
    大致相当于:

    参考:https://blog.csdn.net/chengyq116/article/details/99326733

     

     

     

    import numpy as np
    from functools import reduce
    #from functools import
    def prod(x, y):
        return x*y
    print(reduce(prod, [2, 4, 5, 7, 12]))
    
    输出3360
    

     

     

      

  • 相关阅读:
    JAVA中的继承
    各种浏览器设置背景颜色线性渐变的方式
    JavaScript原型链
    JavaScript运算符
    QQ聊天:终结编程语言和编程职业
    virutal dom patch
    关于编辑器和语言的一些启示
    node-webkit 资源
    我的程序,你的生活
    过早优化是万恶之源
  • 原文地址:https://www.cnblogs.com/Li-JT/p/15060987.html
Copyright © 2020-2023  润新知