您的位置:首页 > 编程语言 > Python开发

Python中filter与lambda的结合使用

2017-08-11 23:04 357 查看
filter是Python的内置方法。官方定义是:

filter(function or None, sequence) -> list, tuple, or string
Return 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 False
filter(lambda x: f(x), [-1, 0, 1]) #[1]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: