本文摘自php中文网,作者黄舟,侵删。
Python中有关filter的用法详解1 2 3 4 5 | 1 class filter ( object )
2 | filter (function or None , iterable) - - > filter object
3 |
4 | Return an iterator yielding those items of iterable for which function(item)
5 | is true. If function is None , return the items that are true.
|
filter读入iterable所有的项,判断这些项对function是否为真,返回一个包含所有为真的项的迭代器。如果function是None,返回非空的项。
1 2 3 | 1 In [ 2 ]: import re
2 In [ 3 ]: i = re.split( ',' , "123,,123213,,,123213," )
3 In [ 4 ]: i4 Out[ 4 ]: [ '123' , ' ', ' 123213 ', ' ', ' ', ' 123213 ', ' ']
|
这时,列表i内包含空串。
1 2 | 1 In [ 7 ]: print ( * filter ( None , i))
2 123 123213 123213
|
这时filter把列表中的空串过滤掉了,得到一个只含非空串的迭代器。
1 2 | In [ 9 ]: print ( list ( filter ( lambda x:x = = '', i)))
[' ', ' ', ' ', ' ']
|
由于lambda对空串为真,所以filter把非空串过滤掉,只剩下空串。
以上就是Python中有关filter的用法详解的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python如何实现网络爬虫
Python文件的三种可读可写模式的特点及区别
Python连接mysql的方式总结
不可错过的十本Python好书
Python字符串的格式化的详细介绍
Python中xlwt设置excel单元格字体及格式方法
Python爬虫如何设置代理
Python怎么换行写代码
Python如何设置曲线样式
django数据库连接丢失的问题解决(示例讲解)
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python中有关filter的用法详解