Home  >  Article  >  Backend Development  >  Detailed explanation of the usage of filter in Python

Detailed explanation of the usage of filter in Python

黄舟
黄舟Original
2017-08-23 13:19:193014browse


Detailed explanation of the usage of filter in Python

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 reads in all items of iterable, determines whether these items are true for function, and returns a list containing all items that are true Iterator of items. If function is None, returns a non-empty item.

1 In [2]: import re
2 In [3]: i = re.split(',',"123,,123213,,,123213,")
3 In [4]: i4 Out[4]: ['123', '', '123213', '', '', '123213', '']

At this time, list i contains an empty string.

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

At this time, the filter filters out the empty strings in the list and obtains an iterator containing only non-empty strings.

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

Since lambda is true for empty strings, filter filters out non-empty strings, leaving only empty strings.

The above is the detailed content of Detailed explanation of the usage of filter in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn