python3中reduce函数用法

reduce函数用途:对迭代对象中的元素从左至右两两送入参数1传入的function中进行运算


导入reduce函数:

from functools import reduce

reduce函数使用方法:help(reduce)

Help on built-in function reduce in module _functools:
reduce(...)
    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.

参数1:function句柄,用于完成迭代对象中两个元素之间的操作

参数2:迭代对象


使用实例:

1、使用reduce完成列表求和

from functools import reduce

x = list(range(1, 11))
print(x)
print(sum(x))


def add_op(i, j):
    '''定义列表中两个元素之间的加法操作'''
    return i + j


print(reduce(add_op, x))


输出结果如下:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
55
55

2、使用reduce完成列表的合并

x = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
    [16, 17, 18, 19, 20]
]

# 将x中的各个元素合并为一个列表
# 通常采用的做法如下
res = []
for e in x:
    res.extend(e)
print(res)


# 采用reduce合并列表
def union_list(l1, l2):
    return l1 + l2


res = reduce(union_list, x)
print(res)

输出结果如下:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

 

你可能感兴趣的:(python编程,python3,reduce)