Python中filter与lambda的结合使用
2017-08-11 23:04
357 查看
filter是Python的内置方法。官方定义是:
第一个参数为
第一个参数为function的情形,如果function(item)为True,则满足过滤条件。此时的lambda函数的形式是:
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]
相关文章推荐
- 【python】详解lambda匿名函数以及结合map、reduce、filter、sorted等使用
- Python list--> Filter , Map , Reduce 使用笔记 (lambda )
- Python 中的 map, reduce, zip, filter, lambda基本使用方法
- python sorted函数(结合使用lambda和operator.itemgetter()来对字典进行排序)
- Python中filter、lambda、map、reduce的使用
- Python中reduce与lambda的结合使用
- 简单介绍Python中的filter和lambda函数的使用
- Python中map与lambda的结合使用
- Python高阶函数(Map、Reduce、Filter)和lambda函数一起使用 ,三剑客
- python中dict和lambda结合的小例子
- xheditor使用与python结合使用
- python内置函数:lambda、map、filter
- Python特殊语法:filter、map、reduce、lambda [转]
- python中的map,filter,reduce,lambda (转)
- Python特殊语法:filter、map、reduce、lambda [转]
- Python特殊语法:filter、map、reduce、lambda [转]
- python—filter, lambda
- Python 猜价格游戏:while 结合 if学习使用(2)
- Python特殊语法:filter、map、reduce、lambda [转]
- Python:通过计算阶乘来学习lambda和reduce这两个函数的使用