In Python programming, thefilter()
Functions are a useful tool for filtering iterable objects (e.g., lists, tuples, etc.) for elements that satisfy a specific condition and returning a new iterable object containing the elements that satisfy the condition. In this article, we'll dive into thefilter()
function, provides detailed example code, and discusses its practical application in Python programming.
What is the filter() function?
filter()
function is one of Python's built-in functions with the following general syntax:
filter(function, iterable)
where the meaning of the parameters is as follows:
-
function
: A function for filtering elements that returnsTrue
maybeFalse
。 -
iterable
: The iterable object to be filtered.
filter()
function willfunction
The function is applied to theiterable
and returns an iterator containing the elements that satisfy the condition. This is only possible if thefunction
function returnsTrue
The element is included in the result only when it is.
basic usage
through (a gap)filter()
Start with the basic usage of the function and learn how to use it to filter the elements in an iterable object.
1. Filtering out even numbers
# Define a function that determines whether a number is even or not def is_even(x): return x % 2 == 0 # Create a list of integers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Use the filter() function to apply the is_even function to all numbers in the list even_numbers = filter(is_even, numbers) # Convert results to lists even_numbers_list = list(even_numbers) print(even_numbers_list) # Output: [2, 4, 6, 8, 10]
In this example, a function is first definedis_even(x)
that is used to determine if a number is even. Then, a list is created containing the integersnumbers
. Next, use thefilter()
function willis_even
The function is applied to thenumbers
for each number in the list and stores the result in theeven_numbers
center. Finally, it will beeven_numbers
Convert to listeven_numbers_list
to see the filtered even numbers.
2. Sifting out words containing specific letters
# Define a function that determines whether a word contains a specific letter or not def contains_letter(word, letter): return letter in word # Create a list containing words words = ["apple", "banana", "cherry", "date", "grape"] # Use the filter() function to apply the contains_letter function to the words in the list filtered_words = filter(lambda x: contains_letter(x, "a"), words) # Convert results to lists filtered_words_list = list(filtered_words) print(filtered_words_list) # Output: ['apple', 'banana', 'date', 'grape']
In this example, a function is definedcontains_letter(word, letter)
that is used to determine whether a word contains a particular letter. Then, a list is created that contains the wordwords
. Next, use thefilter()
function filters out words containing the letter "a" and stores the results in thefiltered_words
center. Finally, it will befiltered_words
Convert to listfiltered_words_list
to see the filtered words.
Lambda function in combination with filter() function
In practical programming, it is common to use Lambda functions with thefilter()
functions are used in combination to quickly filter elements in a row.Lambda functions are lightweight functions that are typically used for simple operations.
1. Use the Lambda function to filter out odd numbers
# Create a list of integers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Use the filter() function and the Lambda function to filter out odd numbers odd_numbers = filter(lambda x: x % 2 != 0, numbers) # Convert results to lists odd_numbers_list = list(odd_numbers) print(odd_numbers_list) # Output: [1, 3, 5, 7, 9]
In this example, a list is created containing integersnumbers
. Then, use thefilter()
function and the Lambda function that filters out all odd numbers and stores the result in theodd_numbers
center. Finally, it will beodd_numbers
Convert to listodd_numbers_list
to see the filtered odd numbers.
2. Use the Lambda function to filter out words containing specific letters
# Create a list containing words words = ["apple", "banana", "cherry", "date", "grape"] # Use the filter() function and the Lambda function to filter out single words that contain the letter "a". classical Chinese poem filtered_words = filter(lambda x: "a" in x, words) # Convert results to lists filtered_words_list = list(filtered_words) print(filtered_words_list) # Output: ['apple', 'banana', 'date', 'grape']
In this example, a list is created containing the wordswords
. Then, use thefilter()
and Lambda functions to filter out words containing the letter "a" and store the results in thefiltered_words
center. Finally, it will befiltered_words
Convert to listfiltered_words_list
to see the filtered words.
caveat
filter()
The function returns an iterator, so it needs to be converted to a list or other iterable object in order to see the results.filter()
The function does not modify the original iterable object, but returns a new iterable object containing the elements that satisfy the conditions. The original object remains unchanged.If you want to filter out elements that satisfy more than one condition, you can use multiple
filter()
function, or use a Lambda function to combine multiple conditions.
Practical application scenarios
When it comes to practical application scenarios, thefilter()
Functions can be powerful in many situations, and the following are some more detailed descriptions and corresponding rich sample code:
1. Data screening
Scene Description:
In data processing, it is often necessary to filter out data that meets specific conditions, such as filtering out numbers, dates, text, etc. that meet a certain threshold.filter()
Functions are a powerful tool for easy data filtering.
Sample code:
# Suppose there is a dictionary containing grades that needs to be filtered for passing grades grades = {"Alice": 85, "Bob": 92, "Charlie": 78, "David": 88} # Define a function to determine if a grade is passing or failing def is_passing(grade): return grade >= 70 # Use the filter() function to apply the is_passing function to the dictionary values passing_grades = dict(filter(lambda x: is_passing(x[1]), ())) print(passing_grades) # Output: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88}
In this example, there is a dictionary containing gradesgrades
, which needs to be filtered for passing grades. A function is definedis_passing(grade)
that is used to determine if the grade is passing (greater than or equal to 70). Then, the results of the test are calculated using thefilter()
function willis_passing
function is applied to the values of the dictionary with theitems()
method converts the result to a dictionary. In the end, the dictionary containing the passing grade is obtainedpassing_grades
。
2. Data cleansing
Scene Description:
In data processing, data cleansing is often required to remove unwanted or invalid data.filter()
Functions can be used for data cleansing to filter out rows of data that meet specific conditions.
Sample code:
# Suppose there is a list containing student information that needs to be filtered for students between the ages of 18 and 25 years old class Student: def __init__(self, name, age): = name = age # Create a list of student objects students = [ Student("Alice", 22), Student("Bob", 19), Student("Charlie", 26), Student("David", 21) ] # Define a function to filter students between the ages of 18 and 25 years old def is_age_between_18_and_25(student): return 18 <= <= 25 # Apply the is_age_between_18_and_25 function to the list of student objects using the filter() function filtered_students = list(filter(is_age_between_18_and_25, students)) for student in filtered_students: print(f"{}, {} years old") # Output: # Alice, 22 years old # Bob, 19 years old # David, 21 years old
In this example, there is a list of objects containing student informationstudents
, needs to filter out students between the ages of 18 and 25. A function is definedis_age_between_18_and_25(student)
that is used to determine if the student's age is within the specified range. Then, the age of the student is determined using thefilter()
function willis_age_between_18_and_25
function is applied to a list of student objects and gets a list of students that satisfy the conditionfiltered_students
。
3. Authority control
Scene Description:
In web applications, it is often necessary to filter what can be accessed based on user permissions.filter()
Functions can be used for permission control to filter out content that the user has permission to access.
Sample code:
# Suppose there is a list of dictionaries containing articles and user permissions articles = [ {"title": "Article 1", "access_level": "public"}, {"title": "Article 2", "access_level": "private"}, {"title": "Article 3", "access_level": "public"}, {"title": "Article 4", "access_level": "restricted"}, ] # Assume that the current user has both "public" and "restricted" privileges. user_permissions = ["public", "restricted"] # Define a function that filters articles that the user has permission to access def has_access(article): return article["access_level"] in user_permissions # Use the filter() function to apply the has_access function to a list of articles accessible_articles = list(filter(has_access, articles)) for article in accessible_articles: print(article["title"]) # Output: # Article 1 # Article 4
In this example, there is a list of dictionaries containing articles and user permissionsarticles
and a list of the permissions the current user hasuser_permissions
. A function is definedhas_access(article)
, which is used to determine if the article is within the user's permissions. Then, use thefilter()
function willhas_access
function is applied to the list of articles and gets the list of articles that the user has permission to accessaccessible_articles
。
4. Data-processing pipeline
Scene Description:
In a data processing pipeline, it is often necessary to process data in multiple steps, such as filtering, transforming, and sorting.filter()
Functions can be used for filtering steps in the data processing pipeline, making the code more modular and maintainable.
Sample code:
# Suppose there is a list containing numbers and you need to filter out the even numbers and calculate their squares numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Define a function to filter out even numbers def is_even(x): return x % 2 == 0 # Define a function to square def square(x): return x ** 2 # Use the filter() function to filter out even numbers and then use the map() function to calculate the square filtered_numbers = filter(is_even, numbers) squared_numbers = map(square, filtered_numbers) # Convert results to lists squared_numbers_list = list(squared_numbers) print(squared_numbers_list) # Output: [4, 16, 36, 64, 100]
In this example, a function is first definedis_even(x)
that is used to filter out even numbers. Then, a function is definedsquare(x)
, which is used to calculate squares. Use thefilter()
function to filter out even numbers and then use themap()
function calculates the square. This allows the filtering and transformation steps to be separated in the data processing pipeline, making the code clearer and more maintainable.
summarize
filter()
Functions are a useful tool in Python for filtering the elements of an iterable object that satisfy specific conditions and return a new iterable object. Through this article, it has been understood that thefilter()
Basic Usage of Functions, Lambda Functions vs.filter()
Combined use of functions and practical application scenarios.
This article on the specific use of the Python filter function is introduced to this article, more related Python filter function content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!