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

Detailed explanation of the usage of filter in Python

黄舟
Release: 2017-08-23 13:19:19
Original
3101 people have browsed it


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.
Copy after login

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', '']
Copy after login

At this time, list i contains an empty string.

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

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)))
['', '', '', '']
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template