码迷,mamicode.com
首页 > 编程语言 > 详细

Python filter用法

时间:2017-08-23 10:38:19      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:import   ems   返回   yield   lam   func   ret   iterator   过滤   

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 In [2]: import re
2 In [3]: i = re.split(,,"123,,123213,,,123213,")
3 In [4]: i
4 Out[4]: [123, ‘‘, 123213, ‘‘, ‘‘, 123213, ‘‘]

这时,列表i内包含空串。

1 In [7]: print(*filter(None, i))
2 123 123213 123213

这时filter把列表中的空串过滤掉了,得到一个只含非空串的迭代器。

In [9]: print(list(filter(lambda x:x==‘‘, i)))
[‘‘, ‘‘, ‘‘, ‘‘]

由于lambda对空串为真,所以filter把非空串过滤掉,只剩下空串。

Python filter用法

标签:import   ems   返回   yield   lam   func   ret   iterator   过滤   

原文地址:http://www.cnblogs.com/chenhaoran-the-prophet/p/7416426.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!