Python 进阶 (三) 函数式编程之 reduce()

一、前言

官方解释如下:

Apply function of two arguments cumulatively to the items of 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). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.

格式: creduce (func, seq[, init()])

reduce()函数即为化简函数,它的执行过程为:每一次迭代,都将上一次的迭代结果(注:第一次为init元素,如果没有指定 init 则为 seq 的第一个元素)与下一个元素一同传入二元func函数中去执行。在reduce()函数中,init 是可选的,如果指定,则作为第一次迭代的第一个元素使用,如果没有指定,就取 seq 中的第一个元素。

二、举例

有一个序列集合,例如[1,1,2,3,2,3,3,5,6,7,7,6,5,5,5],统计这个集合所有键的重复个数,例如 1 出现了两次,2 出现了两次等。大致的思路就是用字典存储,元素就是字典的 key,出现的次数就是字典的 value。方法依然很多第一种:for 循环判断

def statistics(lst):   dic = {}   for k in lst:     if not k in dic:       dic[k] = 1    else:       dic[k] +=1  return diclst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5] print(statistics(lst)) 

第二种:比较取巧的,先把列表用set方式去重,然后用列表的count方法。

def statistics2(lst):   m = set(lst)   dic = {}   for x in m:     dic[x] = lst.count(x)   return diclst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5] print statistics2(lst) 

第三种:用reduce方式

def statistics(dic,k):  if not k in dic:    dic[k] = 1  else:    dic[k] +=1  return diclst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]print reduce(statistics,lst,{}) #提供第三个参数,第一次,初始字典为空,作为statistics的第一个参数,然后遍历lst,作为第二个参数,然后将返回的字典集合作为下一次的第一个参数或者 d = {} d.extend(lst) print reduce(statistics,d) #不提供第三个参数,但是要在保证集合的第一个元素是一个字典对象,作为statistics的第一个参数,遍历集合依次作为第二个参数 

通过上面的例子发现,凡是要对一个集合进行操作的,并且要有一个统计结果的,能够用循环或者递归方式解决的问题,一般情况下都可以用reduce方式实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值