栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python中reduce()函数用法详解

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python中reduce()函数用法详解

reduce()源码:

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

        从上述可以看到,reduce()有三个参数,第一个是函数function,第二个是序列sequence,第三个是initial,为初始值,默认为None

        reduce(func,lst),其中func必须至少有两个参数。每次func计算的结果继续和序列的下⼀个元素做累积计算。

注意:reduce()传⼊的参数func必须至少接收2个参数。

需求:计算 list1 序列中各个数字的累加和。

示例代码1:

import functools

list1 = [1, 2, 3, 4, 5]


#  方法一
def func(a, b):
    return a + b


result = functools.reduce(func, list1)
print(result)  # 15

# 方法二
result2 = functools.reduce(lambda x, y: x + y, list1)
print(result2)

运行结果:

示例代码2:

import functools

list1 = [1, 2, 3, 4, 5]


#  方法一
def func(a, b):
    return a * b


result = functools.reduce(func, list1)
print(result)  # 15

# 方法二
result2 = functools.reduce(lambda x, y: x * y, list1)
print(result2)

运行结果:

示例代码3:

import functools

list1 = [1, 2, 3, 4, 5]
list2 = [1, 1, 1, 1, 1]
list3 = [0, 0, 0, 0, 0]
list4 = [0, 0, 0, 0, 1]

result1 = functools.reduce(lambda x, y: x & y, list1)
result2 = functools.reduce(lambda x, y: x & y, list2)
result3 = functools.reduce(lambda x, y: x | y, list3)
result4 = functools.reduce(lambda x, y: x | y, list4)
print(result1)
print(result2)
print(result3)
print(result4)

运行结果:

示例代码4:

from functools import reduce


def add(x, y):
    return x + y


a = [1, 2, 3, 4, 5]

#  reduce()两个参数
ret1 = reduce(add, a)
print(ret1)

#  reduce()三个参数
ret2 = reduce(add, a, 6)
print(ret2)

运行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1022715.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号