当前位置:网站首页>Lambda function perfect use guide
Lambda function perfect use guide
2022-06-12 06:56:00 【The way of Python data】
source : Radish chowder
Today we are going to study Python Medium lambda function , And discuss the advantages and limitations of using it
What is? Python Medium Lambda function
lambda Function is an anonymous function ( namely , No name definition ), It can take any number of parameters , But unlike ordinary functions , It just evaluates and returns an expression
Python Medium lambda The function uses the following syntax to express :
lambda Parameters : expression
lambda The function consists of three elements :
keyword lambda: And ordinary functions def similar
Parameters : Support passing location and keyword parameters , Like ordinary functions
Text : Expressions that deal with definite parameters
It should be noted that , Ordinary functions are different , There is no need to bracket lambda The parameters of the function are enclosed , If lambda A function has two or more arguments , We list them with commas
We use lambda Function only evaluates a short expression ( Ideally , A single ) And only calculate once , This means that we will not reuse this function in the future . Generally speaking, we will lambda Functions are passed as arguments to higher-order functions ( Functions that accept other functions as arguments ), for example Python Built in functions , Such as filter()、map() or reduce() etc.
Python Medium Lambda How functions work
Let's look at a simple lambda Example of function :
lambda x: x + 1Output:
<function __main__.<lambda>(x)>above lambda Function takes an argument , Incrementing it 1, And then return the result
It is the following with def and return A simpler version of the normal function of the keyword :
def increment_by_one(x):
return x + 1 So far our lambda function lambda x: x + 1 Just create a function object , Don't return anything , This is because we have no parameters for it x Provide any value ( Parameters ). Let's assign a variable first , Pass it to lambda function , Look what we got this time :
a = 2
print(lambda x: a + 1)Output:
<function <lambda> at 0x00000250CB0A5820>our lambda The function did not return as we expected 3, Instead, it returns the function object itself and its memory location , You can see that this is not a call lambda The right way to function . To pass parameters to lambda function , Execute it and return the result , We should use the following syntax :
(lambda x: x + 1)(2)Output:
3Although our lambda The arguments to the function are not enclosed in parentheses , But when we call it , We will be in lambda Add parentheses around the entire construction of the function and the arguments we pass to it
Another thing to note in the above code is , Use lambda function , We can execute the function immediately after it is created and receive the result . This is called immediate call function execution ( or IIFE)
We can create a with multiple parameters lambda function , under these circumstances , We use commas to separate the parameters in the function definition . When we execute such a lambda Function time , We list the corresponding parameters in the same order , And separate them with commas :
(lambda x, y, z: x + y + z)(3, 8, 1)Output:
12You can also use lambda Function to perform conditional operations . Here's a simple one if-else Functional lambda simulation :
print((lambda x: x if(x > 10) else 10)(5))
print((lambda x: x if(x > 10) else 10)(12))Output:
10
12If there are multiple conditions (if-elif-...-else), We must nest them :
(lambda x: x * 10 if x > 10 else (x * 5 if x < 5 else x))(11)Output:
110But the above way of writing , It makes the code hard to read
under these circumstances , have if-elif-...-else The normal function of the condition set will be the ratio lambda Better choice of function . actually , We can write the... In the above example in the following way lambda function :
def check_conditions(x):
if x > 10:
return x * 10
elif x < 5:
return x * 5
else:
return x
check_conditions(11)Output:
110Although the above function is better than the corresponding lambda Function adds more lines , But it's easier to read
We can lambda Function assigned to a variable , Then call the variable as a normal function :
increment = lambda x: x + 1
increment(2)Output:
3But according to Python Code PEP 8 Style rules , It's a bad practice
The use of assignment statements eliminates lambda Expressions are relative to explicit def The only benefit statement can provide ( namely , It can be embedded in larger expressions )
So if we really need to store a function for further use , We'd better define an equivalent ordinary function , Rather than lambda Function assigned to variable
Lambda Function in Python Application in
with filter() Functional Lambda
Python Medium filter() The function takes two arguments :
Functions that define filter conditions
An iteratable object on which a function runs
Run this function , We get a filter object :
lst = [33, 3, 22, 2, 11, 1]
filter(lambda x: x > 10, lst)Output:
<filter at 0x250cb090520>To get a new iterator from the filter object , And all the items in the original iterator meet the predefined conditions , We need to pass the filter object to Python Corresponding functions of the standard library :list()、tuple()、set ()、frozenset() or sorted()( Returns a sorted list )
Let's filter a list of numbers , Only select greater than 10 And returns a list sorted in ascending order :
lst = [33, 3, 22, 2, 11, 1]
sorted(filter(lambda x: x > 10, lst))Output:
[11, 22, 33]We don't have to create a new iteratible object of the same type as the original object , In addition, we can store the result of this operation in a variable :
lst = [33, 3, 22, 2, 11, 1]
tpl = tuple(filter(lambda x: x > 10, lst))
tplOutput:
(33, 22, 11)with map() Functional Lambda
We use Python Medium map() Function to perform specific operations on each project that can be iterated . Its grammar and filter() identical : A function to be executed and an iteratable object to which the function applies .
map() The function returns a map object , We can pass this object to the corresponding Python Function to get a new iteration from it :list()、tuple()、set()、frozenset() or sorted()
And filter() The function is the same , We can map Object to extract iteratable objects of different types from the original type , And assign it to variables .
Here's how to use map() The function multiplies each item in the list by 10 And assign the mapped value to the variable as tpl Example of tuple output for :
lst = [1, 2, 3, 4, 5]
print(map(lambda x: x * 10, lst))
tpl = tuple(map(lambda x: x * 10, lst))
tplOutput:
<map object at 0x00000250CB0D5F40>
(10, 20, 30, 40, 50)map() and filter() An important difference between functions is that the first function always returns iterations of the same length as the original function . So because pandas Series Objects are also iteratable , We can do it in DataFrame Apply on column map() Function to create a new column :
import pandas as pd
df = pd.DataFrame({'col1': [1, 2, 3, 4, 5], 'col2': [0, 0, 0, 0, 0]})
print(df)
df['col3'] = df['col1'].map(lambda x: x * 10)
dfOutput:
col1 col2
0 1 0
1 2 0
2 3 0
3 4 0
4 5 0
col1 col2 col3
0 1 0 10
1 2 0 20
2 3 0 30
3 4 0 40
4 5 0 50Of course, the same results should be obtained in the above cases , You can also use apply() function :
df['col3'] = df['col1'].apply(lambda x: x * 10)
dfOutput:
col1 col2 col3
0 1 0 10
1 2 0 20
2 3 0 30
3 4 0 40
4 5 0 50We can also create a new... For another column based on certain conditions DataFrame Column , For the following code , We can use it interchangeably map() or apply() function :
df['col4'] = df['col3'].map(lambda x: 30 if x < 30 else x)
dfOutput:
col1 col2 col3 col4
0 1 0 10 30
1 2 0 20 30
2 3 0 30 30
3 4 0 40 40
4 5 0 50 50with reduce() Functional Lambda
reduce() Function and functools Python Module related , It works as follows :
Operate on the first two items of the iteratable object and save the results
Operate on the saved results and the next iteration
In this way, on a value pair , Until all projects use iterative
This function has the same two parameters as the first two functions : A function and an iteratable object . But unlike the previous function , This function does not need to be passed to any other function , Directly return the result scalar value :
from functools import reduce
lst = [1, 2, 3, 4, 5]
reduce(lambda x, y: x + y, lst)Output:
15The code above shows that we use reduce() Function to calculate the sum of a list
It should be noted that ,reduce() A function always needs a with two arguments lambda function , And we have to start with functools Python Import it into the module
Python in Lambda The advantages and disadvantages of functions
advantage
It is ideal for evaluating a single expression , Should only be evaluated once
It can be called immediately after definition
Compared with the corresponding common grammar , Its syntax is more compact
It can be passed as a parameter to higher-order functions , for example filter()、map() and reduce()
shortcoming
It cannot execute multiple expressions
It can easily become troublesome , Poor readability , For example, when it includes a if-elif-...-else loop
It cannot contain any variable assignments ( for example ,lambda x: x=0 Will throw a syntax error )
We can't do it for lambda The function provides a document string
summary
To make a long story short , We have discussed in detail in Python Defined and used in lambda Many aspects of functions :
lambda Function and general Python What's the difference between functions
Python in lambda Syntax and analysis of functions
When to use lambda function
lambda How functions work
How to call lambda function
Call function to execute (IIFE) The definition of
How to use lambda Function performs conditional operations , How to nest multiple conditions , And why we should avoid it
Why should we avoid lambda Function assigned to variable
How to integrate lambda Function and filter() Functions together
How to integrate lambda Function and map() Functions together
How we are in pandas DataFrame Use in
With... Passed to it lambda Functional map() function - And the alternative functions used in this case
How to integrate lambda Function and reduce() Functions together
In general Python Upper use lambda The advantages and disadvantages of functions
-------- End --------
边栏推荐
- Unable to load bean of class marked with @configuration
- Scons编译IMGUI
- [image denoising] image denoising based on partial differential equation (PDE) with matlab code
- Torch models trained in higher versions report errors in lower versions
- PowerDesigner connects to entity database to generate physical model in reverse
- 8. form label
- Solution: unsatisfieddependencyexception: error creating bean with name 'authaspect':
- Drawing grid navigation by opencv map reading
- Freshmen are worried about whether to get a low salary of more than 10000 yuan from Huawei or a high salary of more than 20000 yuan from the Internet
- 9 Sequence container
猜你喜欢

VSCode常用插件

上传文件(post表单提交form-data)
![Leetcode: Sword finger offer 67 Convert string to integer [simulation + segmentation + discussion]](/img/32/16751c0a783cc3121eddfe265e2f4f.png)
Leetcode: Sword finger offer 67 Convert string to integer [simulation + segmentation + discussion]

leetcode:剑指 Offer 66. 构建乘积数组【前后缀积的应用】

An error occurred while downloading the remote file The errormessage

Database syntax related problems, solve a correct syntax

VSCode常用插件

Use ms17-010 Eternal Blue vulnerability to infiltrate win7 and establish a permanent back door

Solution: unsatisfieddependencyexception: error creating bean with name 'authaspect':
![Leetcode: Sword finger offer 63 Maximum profit of stock [record prefix minimum and or no brain segment tree]](/img/3a/3bba4fc11469b4cf31c38e35a81ac1.png)
Leetcode: Sword finger offer 63 Maximum profit of stock [record prefix minimum and or no brain segment tree]
随机推荐
Tomato learning notes -vscade configuring makefile (using task.jason and launch.jason)
Curry carries the fourth game of the warriors against the Celtics
What is the difference between < t > and object?
Descscheduler secondary scheduling makes kubernetes load more balanced
VSCode常用插件
A journey of database full SQL analysis and audit system performance optimization
如何更新 Kubernetes 证书
Bid farewell to the charged xshell, and the free function of tabby is more powerful
Recommend 17 "wheels" to improve development efficiency
Flink practice
Solution: content type 'application/x-www-form-urlencoded; charset=UTF-8‘ not supported
初中学历,从不到3K,到月薪30K+,不设限的人生有多精彩
Codeforces Round #793 (Div. 2) A B C
torch在高版本训练的模型在低版本中使用报错
esp32 hosted
Redis basic notes
leetcode:剑指 Offer 60. n个骰子的点数【数学 + 层次dp + 累计贡献】
循环链表和双向链表—课上课后练
6 functions
The difference between get and post and the code implementation of message board

