以下是filter函数的官方文档,注意最后一段,当function不为None时,函数相似于[item for item in iterable if function(item)],function为None时,函数相似于[item for item in iterable if item]。
filter(function, iterable)
Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.
根据官方文档,为了方便理解,自己试着去实现了下,没有带异常处理。分析filter(function, iterable),满足以下条件
根据function生成列表,再根据iterable对列表进行相应处理。
def myFilter(func, seq): if func is None: results = [i for i in seq if i] else: results = [i for i in seq if func(i)] if isinstance(seq, tuple): results = tuple(results) elif isinstance(seq, basestring): results = ''.join(results) return results
运行结果与filter自建函数输出一致。
PRint '-------------------filter------------------------------'print filter(lambda x: x > 4, range(10))print filter(lambda x: x > 4, tuple(range(10)))print filter(None, range(10))print filter(lambda x: x > '3', '12345')print filter(None, '01234')print '-------------------myFilter----------------------------'print myFilter(lambda x: x > 4, range(10))print myFilter(lambda x: x > 4, tuple(range(10)))print myFilter(None, range(10))print myFilter(lambda x: x > '3', '12345')print myFilter(None, '01234')
新闻热点
疑难解答