函数式编程:reduce的使用方法

按照惯例,在学习reduce函数之前在交互模式下看下reduce的文档(万一有坑,可以在开始的时候给填上)

python2 >>>

Help on built-in function reduce in module __builtin__:

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. apply a function of two arguments  必须是两个参数的函数作为第一个参数

2. If initial is present, it is placed before the items of the sequence in the calculation  第三个参数作用是第一次循环的时候的传递给作用函数func(x,y)中的x参数

 

python3 >>> 

与python2作用上没有太大的区别
python3将reduce函数从内置函数中移动到了functools模块中了

 

实例:

1. 计算1~5的和以及10为初始X

#!/usr/bin/env python2.7 
# -*- coding=utf-8 -*-
reduce(lambda x, y:x + y,[1,2,3,4,5],10)



#!/usr/bin/env python3.0
# -*- coding=utf-8 -*-
from functools import reduce
reduce(lambda x, y:x + y,[1,2,3,4,5],10)

2. 统计<这段代码从https://blog.csdn.net/taxueguilai1992/article/details/50382619/ 借鉴过来的,感觉作为例子不错>

#!/usr/bin/env python2.7
# -*- coding=utf-8 -*-

str="an apple a banana three apple a desk"
list=str.split(' ')
def fun(x, y):
    if y in x:
        x[y]=x[y]+1
    else:
        x[y]=1
    return x
result=reduce(fun, list,{})

>>>{'a': 2, 'apple': 2, 'three': 1, 'an': 1, 'desk': 1, 'banana': 1}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值