Home  >  Article  >  Backend Development  >  Detailed explanation of Python filter list usage examples

Detailed explanation of Python filter list usage examples

高洛峰
高洛峰Original
2017-03-06 13:46:582159browse

The example in this article describes the usage of Python filter list. Share it with everyone for your reference, the details are as follows:

Filter list

[mapping-expression for element in source-list if filter-expression ]

Things starting with if are filter expressions, which can be any expression that returns true or false (almost anything in Python). Any filter expression that evaluates to true as an element can be included in the map. Other elements will be ignored, they will not enter the mapping expression, and they will not be included in the output list.

>>> li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
>>> [elem for elem in li if len(elem) > 1]
['mpilgrim', 'foo']
>>> [elem+elem for elem in li if len(elem) > 1]
['mpilgrimmpilgrim', 'foofoo']
>>>

For more detailed examples of Python filter list usage and related articles, please pay attention to 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