首页 > 学院 > 开发设计 > 正文

pythonfilter内建函数

2019-11-14 16:57:55
字体:
来源:转载
供稿:网友

以下是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, 为None, 或者函数。
  • iterable, 为list, tuple, 或者basestring。

根据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')

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表