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)

运行结果:

示例代码5:  【mongo和es语句中使用reduce】

from functools import reduce
from mongoengine import Q
from mongoengine.queryset.visitor import Q
from elasticsearch_dsl import Q as EQ

# query_list = ['x', 'y', 'z']  # 字符串报错:TypeError: unsupported operand type(s) for &: 'str' and 'str'
# query_list = [2, 3]  # 2
# query_list = [2, 3, 4]  # 0
# mongo中使用
query_list = [Q(aa="aa"), Q(bb='bb'), Q(cc='cc'), Q(dd='dd')]  # (Q(**{'aa': 'aa'}) & Q(**{'bb': 'bb'}) & Q(**{'cc': 'cc'}) & Q(**{'dd': 'dd'}))
res = reduce(lambda x, y: x & y, query_list)
print(res)

# es中使用
query_list = [EQ(aa="aa"), EQ(bb='bb'), EQ(cc='cc'), EQ(dd='dd')]  # MatchAll(dd='dd')
res = reduce(lambda x, y: x & y, query_list)
print(res)

运行结果:

  • 4
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值