龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > python编程 >

python中的reduce内建函数使用方法指南(2)

时间:2014-09-01 02:38来源:网络整理 作者:网络 点击:
分享到:
第一种:for循环判断 def statistics(lst): dic = {} for k in lst: if not k in dic: dic[k] = 1 else: dic[k] +=1 return dic lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5] print(statistics(lst)) 第二种:比

第一种:for循环判断

def statistics(lst): 
  dic = {} 
  for k in lst: 
    if not k in dic: 
      dic[k] = 1 
    else: 
      dic[k] +=1 
  return dic 
 
lst = [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 dic 
 
lst = [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 dic 
 
lst = [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方式实现。

reduce函数真是“一位好同志啊”!

精彩图集

赞助商链接