Reduce

python3.6

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

python3中reduce函数存在于functools中, 使用前需要从import导入.

       reduce(function, sequence, initial=None):

           function:函数
  sequence:可迭代数据
  initial :动态参数

    # reduce 处理序列,合并操作.

例: 实现列表相加相乘及指定动态初始值

# reduce 实现列表相加相乘及指定动态初始值
from functools import reduce

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

print(reduce(lambda x, y: x + y, num_list, 2))
print(reduce(lambda x, y: x * y, num_list, 2))


用for和自定义函数解析reduce执行时所作的操作.

#1 for 实现num_list列表相加(固定的处理逻辑 v += n)
num_list = [1, 2, 3, 4, 5]
v = 0  # 固定
for n in num_list:
    v += n

print(v)



#2 自定义函数实现num_list列表相加 (固定的处理逻辑 v += n)
num_list = [1, 2, 3, 4, 5]


def reduce_test(value):
    v = 0  # 固定
    for n in value:
        v += n  # 固定
    return v


print(reduce_test(num_list))



#3 自定义函数实现num_list列表相乘,把固定的逻辑式x*y换成函数multi和匿名函数
num_list = [1, 2, 3, 4, 5]


def multi(x, y):
    return x * y


def reduce_test(func, value):
    v = 1  # 固定
    for n in value:
        v = func(v, n)
    return v


print(reduce_test(multi, num_list))

print(reduce_test(lambda x, y: x * y, num_list))



#4 自定义函数实现num_list列表相乘,固定的初始值改为pop(0)也就是列表的第一位.
num_list = [1, 2, 3, 4, 5]


def multi(x, y):
    return x * y


def reduce_test(func, value):
    v = value.pop(0)  # pop(0)取第一个值 # v = 1  # 固定
    for n in value:
        v = func(v, n)
    return v


print(reduce_test(multi, num_list))



#5 自定义函数实现num_list列表相乘,初始值为动态
num_list = [1, 2, 3, 4, 5]


def multi(x, y):
    return x * y


def reduce_test(func, value, init=None):
    if init is None:
        v = value.pop(0)
    else:
        v = init

    for n in value:
        v = func(v, n)
    return v


print(reduce_test(multi, num_list, 3))

原文地址:https://www.cnblogs.com/IMxY/p/6957942.html