原文:http://www.liuzhongshu.com/code/python-map-filter-reduce.html
python有几个内置的函数很有意思:map/filter/reduce,都是对一个集合进行处理,filter很容易理解用于过滤,map用于映射,reduce用于归并,这几个词还是太抽象了,下面的代码精确的说明了这几个函数的用途:
def map_imp(function, sequence) :
if function is None: return list(sequence)
retvals = []
for element in sequence:
if (function(element)):
retvals.append(element)
return retvals
def reduce_imp(function, sequence) :
arg1 = function(sequence[0])
for arg2 in sequence[1:] :
arg1 = function(arg1, arg2)
return arg1
def filter_imp(function, sequence) :
retvals = []
for element in sequence:
if (function is None and element) or function(element) :
retvals.append(element)
return retvals
对于这种逻辑性强的东西,用语言来描述是无助的,代码则要清晰的多。
具体使用方法可以参考另外一篇:http://www.blogjava.net/rain1102/archive/2009/06/01/279478.html
posted on 2009-06-14 22:08
周锐 阅读(915)
评论(0) 编辑 收藏 所属分类:
Python