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]

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值