1. Preface
lambda
Expressions are a concise and anonymous function expression in Python. They are used to create simple functions, usually used without the need to define a complete function.lambda
The syntax of expressions is very concise and is suitable for writing small functions in one line.
Next, we start from specific examples and understand how to use lambda expressions from shallow to deeper.
2. Basic grammar
lambda parameter1, parameter2, ... : expression
-
lambda
The boot keyword indicates that this is an anonymous function. - The parameters are immediately followed by, separated by commas.
- The colon is followed by the function's expression, that is, the return value.
Equivalent to abbreviationdef
Function definition.
3. Give a simple example:
# Normal functionsdef add(x, y): return x + y # Write it with lambda expressionadd_lambda = lambda x, y: x + y # Callprint(add(2, 3)) # Output: 5print(add_lambda(2, 3)) # Output: 5
In this example,add_lambda
It is equivalent toadd
anonymous function, but it useslambda
Expressions are defined.
4. Common application scenarios
1. Used to sort functions
When we need to sort a list of complex data types such as tuples, dictionaries, etc., we usually uselambda
to define the rules for sorting.
For example, in the parameters of the .sort sort function in the list, use key= a lambda expression to specify the sorting rules.
# Sort by the second element in the tuplepoints = [(1, 2), (3, 1), (5, 4)] (key=lambda x: x[1]) print(points) # Output: [(3, 1), (1, 2), (5, 4)]
In the example of the sort function, we usedlambda
Expressions and listssort
Method, sort a list containing tuples. Next, I will explain the working principle of this example step by step.
sort() method introduction
sort()
is a built-in method for lists in Python, used forOn-siteSort the list (that is, the original list will be modified directly). It can sort list elements according to the default order (i.e., numbers from small to large and strings in dictionary order).
We can usekey
Parameters customize the sorting rules.key
Accepts a function that generates the value used for comparison.
For example, by default,sort()
The method is based on the value sorting of elements:
numbers = [3, 1, 2] () print(numbers) # Output: [1, 2, 3]
However, if we want to sort by custom rules, such as sorting by some element of a tuple (such as a second element), we can usekey
Parameters.
The function of lambda expression
In this example, we want to use a list of multiple tuplespoints
Sort, and the ordering is based on the second element of each tuple (the element with index 1). To implement this function, we uselambda
Expression:
key=lambda x: x[1]
herex
is each tuple in the list,x[1]
Represents the second element of the tuple. We tellsort
Methods should be sorted according to the second element of each tuple.
Detailed explanation
Data structure:
points = [(1, 2), (3, 1), (5, 4)]
This is a list of three tuples, each containing two numbers. For example,(1, 2)
Denotes the coordinates of a point,1
yesx
Coordinates,2
yesy
Coordinates.-
lambda
Expression:key=lambda x: x[1]
-
x
Represents each tuple in the list. -
x[1]
Extract the second element of the tuple. -
lambda
The function of expressions is to tellsort
Method, you only need to consider the second element of each tuple for comparison sorting.
-
-
Sorting process:
sort()
The method starts with the first tuple in the list and calls each tuplelambda x: x[1]
, return the value of the second element as the basis for sorting.Pair tuple
(1, 2)
,lambda
return2
. Pair tuple(3, 1)
,return1
. Pair tuple(5, 4)
,return4
。Then,
sort()
Method according to1
,2
,4
The order of sorts, and the result is:[(3, 1), (1, 2), (5, 4)]
。
Final result:
Sort listpoints
for[(3, 1), (1, 2), (5, 4)]
. This result is sorted from small to large according to the second element of each tuple.
Further expansion
If we want to tupleThe first elementSorting, just need tox[1]
Change tox[0]
:
(key=lambda x: x[0]) print(points) # Output: [(1, 2), (3, 1), (5, 4)]
If you want to achievedescending orderSort, you can setreverse=True
:
(key=lambda x: x[1], reverse=True) print(points) # Output: [(5, 4), (1, 2), (3, 1)]
Summarize
lambda
Expressions are used in sorting functions to concisely define the basis for sorting. By passingkey
Parameters, we can easily customize the sorting rules, such as sorting by a specific element in a tuple.
2. Combined with map, filter, reduce and other functions
lambda
Expressions andmap
、filter
、reduce
The use of contour higher-order functions is a powerful tool in Python programming. Next, we will explain these three functions in detail and their combination.lambda
Usage of .
1. Map() function
map()
Functions are used to apply a function to each element in the iterable object and return a new iterator. It can accept a function and one or more iterable objects (such as lists, tuples).
grammar:
map(function, iterable)
-
function
is a function to be applied to each element. -
iterable
is an iterable object (such as lists, tuples, etc.).
When combinedlambda
When used,lambda
Expressions are passed as an anonymous function tomap()
。
Example: Square each number in the list
nums = [1, 2, 3, 4, 5] # Use lambda expressions and mapssquared = map(lambda x: x**2, nums) # Convert the results to a list and print itprint(list(squared)) # Output: [1, 4, 9, 16, 25]
explain:
-
lambda x: x**2
is an anonymous function used to calculate the square of each number. -
map()
The functions willlambda
Applied tonums
Each element in the list, i.e.1
,2
,3
,4
,5
, and then return the result after each element is squared.
Common function writing equivalent:
def square(x): return x ** 2 squared = map(square, nums) print(list(squared)) # Output: [1, 4, 9, 16, 25]
2. filter() function
filter()
Functions are used to filter elements in an iterable object, keeping those that make the function returnTrue
elements. It also returns an iterator.
grammar:
filter(function, iterable)
-
function
is a function used to test each element, returningTrue
orFalse
。 -
iterable
It is an iterable object that needs to be filtered.
Whenlambda
When using expressions in combination,lambda
Can be used as a filter condition.
Example: Filter out even numbers in the list
nums = [1, 2, 3, 4, 5] # Use lambda expressions and filtersevens = filter(lambda x: x % 2 == 0, nums) # Convert the results to a list and print itprint(list(evens)) # Output: [2, 4]
explain:
-
lambda x: x % 2 == 0
is an anonymous function used to judgex
Whether it is an even number. -
filter()
The functions willlambda
Applied tonums
Each element in the list, returnTrue
The element of is retained, returnFalse
The elements of are filtered out. Therefore, the end result is to retain even numbers2
and4
。
Common function writing equivalent:
def is_even(x): return x % 2 == 0 evens = filter(is_even, nums) print(list(evens)) # Output: [2, 4]
3. Reduce() function
reduce()
Functions are used to accumulate elements in an iterable object and finally merge them into a value. It needs to be importedfunctools
module, because it does not belong to Python's built-in functions.
grammar:
from functools import reduce reduce(function, iterable)
-
function
is a function that requires two parameters to merge the previous calculation result with the next element. -
iterable
It is an iterable object.
Whenlambda
When expressions are combined,lambda
Rules used to define accumulation.
Example: Calculate the accumulated sum of all elements of the list
from functools import reduce nums = [1, 2, 3, 4, 5] # Use lambda expressions and reducetotal = reduce(lambda x, y: x + y, nums) print(total) # Output: 15
explain:
-
lambda x, y: x + y
is an anonymous function that accepts two parametersx
andy
, and return their sum. -
reduce()
The function first takes the first two elements1
and2
Added to get3
, and then3
and3
Added to get6
, and so on until all elements are processed. Finally return the accumulated result15
。
Common function writing equivalent:
def add(x, y): return x + y total = reduce(add, nums) print(total) # Output: 15
Summarize
-
map()
: Apply a function to each element and return the transformation result of each element. Suitable for batch operation. -
filter()
: Filter elements according to conditions, retaining elements that meet the conditions. -
reduce()
: Performs accumulation operations on elements in the sequence, suitable for scenarios where you need to be reduced to a single value.
lambda
Expressions can be conveniently combined with these higher-order functions, reducing code redundancy and explicit definition of functions.
3. Functions used for internal or single-use functions
When the function only needs to be used once, you can use it directlylambda
Expression without defining new function names.
def apply_operation(x, operation): return operation(x) # Pass anonymous functions using lambdaresult = apply_operation(5, lambda x: x * 2) print(result) # Output: 10
5. Summary
lambda
Expressions are used to simplify code, especially for short functions, avoid explicitly defining complete functions. Although it is convenient, when the functions are more complex, it is still recommended to use ordinary function definitions to improve the readability of the code.
This is the end of this article about the detailed explanation of the use of lambda expressions in Python. For more related contents of lambda expressions in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!