Python中filter与lambda的结合使用

来源:互联网 发布:f1 2015知乎 编辑:程序博客网 时间:2024/06/10 07:30

filter是Python的内置方法。官方定义是:

filter(function or None, sequence) -> list, tuple, or stringReturn those items of sequence for which function(item) is true.  If function is None, return the items that are true.  If sequence is a tuple or string, return the same type, else return a list.

第一个参数为None的情形:

filter(None, '101') # '101'filter(None, [True,False]) #[True]filter(None, [True, 0, 1, -1]) #[True, 1, -1]filter(None, (True, 1, 0, -1, False)) #(True, 1, -1)

第一个参数为function的情形,如果function(item)为True,则满足过滤条件。此时的lambda函数的形式是: lambda x: expression(x)。注意到,:左边只能有一个元素x:右边为一个关于x的表达式,且这个表达式的值要么是True, 要么是False.

filter(lambda x: x, [-1, 0, 1]) #[-1, 1]filter(lambda x: not x, [-1, 0, 1]) #[0]def f(x):    return True if x == 1 else Falsefilter(lambda x: f(x), [-1, 0, 1]) #[1]
原创粉丝点击