Get more information
Personal website: Brother Tao talks about Python
Python is a feature-rich programming language that provides many built-in functions to simplify various programming tasks. In Python, map()
, filter()
and reduce()
are a set of very useful functions that allow iterable objects to be Perform operations to transform, filter, and accumulate data.
This article will introduce these three functions in detail, including their basic usage and sample code.
1. map()
function
The map()
function is one of Python’s built-in functions. It is used to apply a function to each element of an iterable object (such as a list, tuple, etc.), and then returns a new Iterable object. This is a very efficient way to transform data.
Basic usage
The basic syntax of the map()
function is as follows:
map(function, iterable, ...)
function
: The function to be applied to the iterable object.iterable
: The iterable object to be mapped.
The map()
function can accept multiple iterable objects, but each iterable object must have the same number of elements. It applies a function
to the corresponding elements of an iterable object and returns an iterator containing all mapped results.
Example
Several examples demonstrate the usage of the map()
function.
Example 1: Convert elements in a list to uppercase
words = ["hello", "world", "python"] capitalized_words = list(map(str.upper, words)) print(capitalized_words)
Output:
['HELLO', 'WORLD', 'PYTHON']
In this example, the str.upper
function is applied to each element of the words
list, converting them to uppercase.
Example 2: Add corresponding elements of two lists
numbers1 = [1, 2, 3, 4] numbers2 = [10, 20, 30, 40] sums = list(map(lambda x, y: x + y, numbers1, numbers2)) print(sums)
Output:
[11, 22, 33, 44]
In this example, the lambda
function is used to add corresponding elements of two lists, producing a new list.
2. filter()
function
The filter()
function is Python’s built-in function, used to filter elements in an iterable object that meet specified conditions, and then return a new iterable object containing the filtered results.
Basic usage
The basic syntax of the filter()
function is as follows:
filter(function, iterable)
function
: A function used to filter elements, which returnsTrue
orFalse
.iterable
: The iterable object to be filtered.
The filter()
function applies the function
to each element in the iterable
and retains those elements that cause the function
to return True
element, generates an iterator containing the filter results.
Example
Below are some examples demonstrating the use of the filter()
function.
Example 1: Filter out even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers)
Output:
[2, 4, 6, 8]
In this example, the lambda
function is used to check whether each element is an even number, and then the filter()
function filters out all elements that meet the condition.
Example 2: Filter out strings with a length greater than or equal to 5
words = ["apple", "banana", "cherry", "date", "elderberry"] long_words = list(filter(lambda x: len(x) >= 5, words)) print(long_words)
Output:
['apple', 'banana', 'cherry', 'elderberry']
In this example, the lambda
function is used to check whether the length of each string is greater than or equal to 5, and then the filter()
function filters out all strings that meet the condition.
3. reduce()
function
The reduce()
function is Python’s built-in function, which is used to perform cumulative operations on elements in an iterable object, apply the specified function in sequence from left to right, and summarize the results into one value. This is useful in certain situations, such as calculating cumulative values or finding max/min values.
Basic usage
The basic syntax of the reduce()
function is as follows:
functools.reduce(function, iterable[, initializer])
function
: A function used for accumulation operations. This function accepts two parameters and returns a result.iterable
: Iterable object to be accumulated.initializer
(optional): Initial value for accumulation.
The reduce()
function applies function
to the elements in iterable
, accumulating from left to right,
The result is passed to the next element. If initializer
is provided, it will be used as the initial value for the accumulation. Otherwise, the first element of iterable
will be used as the initial value.
Example
Below are some examples demonstrating the use of the reduce()
function.
Example 1: Calculate the cumulative product of all elements in a list
from functools import reduce numbers = [1, 2, 3, 4, 5] product = reduce(lambda x, y: x * y, numbers) print(product)
Output:
120
In this example, the lambda
function is used to calculate the cumulative product. The reduce()
function applies the function to each element in the list, cumulatively from left to right.
Example 2: Find the maximum value in a list
from functools import reduce numbers = [42, 17, 8, 96, 23] max_value = reduce(lambda x, y: x if x > y else y, numbers) print(max_value)
Output:
96
In this example, the lambda
function is used to compare two values and return the larger value. The reduce()
function applies the function to each element in the list, looking for the maximum value from left to right.
Summary
map()
, filter()
, and reduce()
are powerful functions in Python that provide a convenient way to handle The elements in the iterable object. These functions are useful in many programming tasks, including data transformation, filtering, and accumulation operations. Proficiency in these functions can make Python programming more efficient and concise.
Python learning route
Get more information
Personal website: Brother Tao talks about Python
If you want to get more and richer information, you can click on the business card below the article and reply [High-quality information] to get a comprehensive learning information package.
Click on the link card below the article and reply [Quality Information] to directly receive the information gift package.