Python内置函数_reduce函数

1. 概念

1.1 描述

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

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

​ 简单说,就是总是代入前两个参数,如果超过两个,则先代入前两个然后返回值,返回值+下一个参数再次倒入,依次类推,得到最后的返回值

注意

​ 在 Python3 中,reduce() 函数已经被从全局名字空间里移除了,它现在被放置在functools模块里,如果想要使用它,则需要通过引入functools模块来调用reduce函数

from functools import reduce

1.2 语法

reduce(function, sequence[, initial])

参数说明

  1. function:函数,有两个参数
  2. sequence:序列,可迭代对象,如列表、元组
  3. initial:可选,初始参数

源码内容

def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
    """
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a 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).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
    """
    pass

1.3 返回值

返回函数计算/执行结果

2. 实例

from functools import reduce


# 1.实现数字相加
# 1.1 两数相加(该函数作为reduce的函数参数)
def add(x,y):
    return x+y
ret01 = reduce(add,[1,2,3,4])   # 计算 1+2+3+4
print(ret01)    # 10


# 2.通过lambda实现
ret02 = reduce(lambda x,y:x+y,[1,2,3,4])
print(ret02)    # 10


# 3.做一个加法函数,可任意数字相加
def addFunc(*args):
    return reduce(lambda x,y:x+y,*args)
ret03 = addFunc([1,2,3,4,5])
print(ret03)    # 15

你可能感兴趣的:(python)