Home >Backend Development >Python Tutorial >List filtering using Python's filter() function

List filtering using Python's filter() function

PHPz
PHPzOriginal
2023-11-18 18:12:151189browse

List filtering using Pythons filter() function

Use Python’s filter() function to filter lists

The filter() function is a high-order function built into Python, used to filter elements that meet specified conditions. And return it as a new list. In list processing, filter() can play a very important role, which can greatly simplify the code and improve efficiency.

The basic syntax of the filter() function is as follows:
filter(function, sequence)

Among them, function is a function used to judge each element in the sequence and return True or False; sequence is an iterable object, such as a list, tuple, etc.

Below we use some specific code examples to demonstrate how to use the filter() function to filter the list:

Example 1: Filter out all even numbers in the list

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

filtered_lst = filter(lambda x: x % 2 == 0, lst)

print(list(filtered_lst))  # 输出结果:[2, 4, 6, 8, 10]

Example 2: Filter out all strings with a length greater than or equal to 5 in the string list

lst = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

filtered_lst = filter(lambda x: len(x) >= 5, lst)

print(list(filtered_lst))  # 输出结果:['banana', 'cherry', 'elderberry']

Example 3: Filter out all dictionaries with an even number in the dictionary list

lst = [{'name': 'Alice', 'age': 20}, {'name': 'Bob', 'age': 25}, {'name': 'Cindy', 'age': 30}]

filtered_lst = filter(lambda x: x['age'] % 2 == 0, lst)

print(list(filtered_lst))  # 输出结果:[{'name': 'Alice', 'age': 20}, {'name': 'Cindy', 'age': 30}]

Example 4: Filter Extract all tuples whose first element is greater than 10 in the tuple list

lst = [(5, 7), (12, 15), (8, 9), (16, 18)]

filtered_lst = filter(lambda x: x[0] > 10, lst)

print(list(filtered_lst))  # 输出结果:[(12, 15), (16, 18)]

Using the filter() function can make the code more concise and efficient, reduce the nesting of loops and if statements, and improve the code's readability Readability and maintainability. But it should be noted that the filter() function returns a filter object, which needs to be converted into a list using the list() function before it can be output or further operated.

The above is the detailed content of List filtering using Python's filter() function. 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