lambda function
What is lambda?
Hello everyone, today I bring you a detailed analysis of lambda expressions in Python. lambda has a wide range of uses in Python, but to be honest, I personally think that the discussion about lambda is not about how to use it, but whether to use it or not. I'm going to share my learning experience with you through a lot of examples, and you'll probably end up coming to the same conclusion as I did.
Okay, first of all, let's understand the basic definition, what is lambda?
Lambda expresses a special syntax used in Python to create anonymous functions. We will refer to the lambda syntax itself as a lambda expression, and the functions that we get from it as lambda functions.
In fact, to summarize, a lambda can be understood as a small anonymous function thatA lambda function can take any number of arguments, but can only have one expression. I'm guessing that those of you with JavaScript ES6 experience will sound very friendly, and the specific function expressions are as follows:
Template:lambda argument: manipulate(argument)
Argument: the argument is the parameter passed to the anonymous function, followed by a colon indicating what we can do with the argument.
Let's refer to the definition of templates and parameters above, and go straight to the simplest example.
add_one = lambda x:x+1 # 1 parameter to perform the operation +1 add_nums = lambda x,y:x+y # 2 arguments, performs the operation as a sum print(add_one(2)) # call add_one print(add_nums(3,7)) # call add_nums >>> 3 10
Compared to what you have found the characteristics of the lambda anonymous function, that is, for the simpler functions, without having to define a single line can be written down, passing parameters and execution methods in one fell swoop!
Lambda Usage Explained
Next let's look at lambda in action, in my own experience with lambda, never having used it alone, theIn general, lambda is used in conjunction with awesome built-in functions like map, filter, reduce, as well as data structures like dict, list, tuple, set, etc.That's how you get the most out of it.
Well, without further ado, let's look at them one by one
lambda + map
First out of the gate is the combination lambda+map, first look at the example below:
numbers = [1,2,3,4,5] add_one = list(map(lambda n:n+1,numbers)) #map(fun,sequence) print(list(add_one)) print(tuple(add_one)) Out: [2, 3, 4, 5, 6] (2, 3, 4, 5, 6)
This is an example from our last installment, implementing an array (tuple) with +1 for each element, so let's recall the use of mapmap(fun,sequence)
The fun is the passed method, the sequence is an iterable sequence, and here our fun is an anonymous function.lambda n:n+1
Here is a perfect explanation of why lambda was designed in the first place, because without lambda, our solution would look like this.
def add(num): return num+1 numbers = [1,2,3,4,5] add_one = list(map(add,numbers)) print(add_one) print(tuple(add_one))
Obviously, the add method is a bit redundant here, so it's a good idea to use a lambda instead. Let's take a look at the next example, which is a small piece of code I wrote when I was backing up my logs, and the naming is not very standardized:
from datetime import datetime as dt logs = ['serverLog','appLog','paymentLog'] format ='_{}.py'.format(().strftime('%d-%m-%y')) result =list(map(lambda x:x+format,logs)) # String splicing with map+lambda print(result) Out:['serverLog_11', 'appLog_11', 'paymentLog_11']
Here it's pretty much the same as the plus 1 example from earlier, but switched to string concatenation, however I'm not using lambda here as a good solution, and we'll end up saying that by now you should have some feel for map + lambda, so let's go back to an example of interacting with a dict dictionary:
person =[{'name':'Lilei', 'city':'beijing'}, {'name':'HanMeiMei', 'city':'shanghai'}] names=list(map(lambda x:x['name'],person)) print(names) Out:['Lilei', 'HanMeiMei']
Well, see here for the use of map + lambda we have been very clear that should ~
lambda + filter
The combination of lambda and filter is also common for specific filtering conditions, now let's look at the filter example from the previous article and it should be well understood:
numbers = [0, 1, 2, -3, 5, -8, 13] # Extracting odd numbers result = filter(lambda x: x % 2, numbers) print("Odd Numbers are :",list(result)) # Extract even numbers result = filter(lambda x: x % 2 == 0, numbers) print("Even Numbers are :",list(result)) # Extract positive numbers result = filter(lambda x: x>0, numbers) print("Positive Numbers are :",list(result)) Out:Odd Numbers are : [1, -3, 5, 13] Even Numbers are : [0, 2, -8] Positive Numbers are : [1, 2, 5, 13]
Here is nothing more than we filter (fun, sequence) inside the fun replaced by our lambda, just the function part of the lambda (x%2,x%2 == 0,x>0) are able to return True or False to determine the requirements to meet the requirements of the fiter, using the example of Li Lei and Han Mei Mei just now is also a reasoning:
person =[{'name':'Lilei', 'city':'beijing'}, {'name':'HanMeiMei', 'city':'shanghai'}] names=list(filter(lambda x:x['name']=='Lilei',person)) # Extracting information about Lee Ray print(names) Out:[{'name': 'Lilei', 'city': 'beijing'}]
lambda + reduce
Or let's look at the example from the previous post:
from functools import reduce # Only Python 3 numbers = [1,2,3,4] result_multiply = reduce((lambda x, y: x * y), numbers) result_add = reduce((lambda x,y: x+y), numbers) print(result_multiply) print(result_add) Out:24 10
This example implements list for cumulative sum and cumulative multiplication using lambda and reduce together.
It's interesting that this example has two sides, one showing how lambda and reduce can be used together, and the other leading to the point I want to make next: is lambda really worth using? How should it be used?
Avoid overuse of lambda
You've already seen lambda in action with the examples above, but here's what I'd like to share with you.I think the disadvantages of lambda slightly outweigh the advantages and overuse of lambda should be avoided.
First of all, this is just my personal opinion haha, I hope you understand, why I say this, first of all let's take the lambda method and the regular def to do a comparison, I found the main differences between lambda and def are as follows:
- Can be passed immediately (no variables required)
- One line of code, clean (not necessarily efficient)
- can be returned automatically without the need to return
- A lambda function does not have a function name
About the advantages we can see, I mainly want to talk about its shortcomings, first of all, from the real needs, we do not need lambda in most of the time, because there can always find a better alternative, now we look at the example of lambda + reduce just now together, we use lambada to achieve the following results:
from functools import reduce # Only Python 3 numbers = [1,2,3,4] result_multiply = reduce((lambda x, y: x * y), numbers) result_add = reduce((lambda x,y: x+y), numbers)
Simplicity and efficiency are not achieved here with lambda, because we have ready-made sum and mul methods available:
from functools import reduce from operator import mul numbers = [1,2,3,4] result_add = sum(numbers) result_multiply =reduce(mul,numbers) print(result_add) print(result_multiply) Out: 10 24
The result is the same, but obviously the scheme with sum and mul is more efficient. To illustrate with another common example, if we have a list storing various colors, and now we are required to capitalize the first letter of each color, if we write it out in lambda it looks like this:
colors = ['red','purple','green','blue'] result = map(lambda c:(),colors) print(list(result)) Out:['Red', 'Purple', 'Green', 'Blue'] Looks good.,It's pretty simple.,But we have a better way.: colors = ['red','purple','green','blue'] result = [() for c in colors] print(result) Out:['Red', 'Purple', 'Green', 'Blue'] expense or outlaysortedAlso handles initialization irregularities,It doesn't even have to be sorted.: colors = ['Red','purple','Green','blue'] print(sorted(colors,key=)) Out:['blue', 'Green', 'purple', 'Red']
There is another main reason: lambda functions don't have function names. So in the code handover, project migration scenarios will bring a lot of difficulties to the team, write a function add_one () is no harm, because everyone can easily understand, know that it is the implementation of the +1 function, but if the team you are responsible for their own module in the use of a lot of lambda, it will bring a lot of trouble for other people to understand the trouble
Scenarios suitable for lambda
Then again, existence makes sense, so what are the scenarios that really require us to use lambda:
- The method you need is very simple (+1, string splicing, etc.), and the function is not worth having a name for!
- Using lambda expressions will be easier to understand than function names we can think of
- Apart from lambda, there is no function provided by python that accomplishes the purpose
- All members of the team have mastered lambda, and everyone agrees that you should use the
Another scenario that works very well is when creating the illusion to others that you are professional, for example:
Hey, little brother, I heard you learned Python. Do you know lambda? No? No way, it's a waste of time!
Come on, come on, let me tell you about it. Omit 10,000 words here.
summarize
Today we explained the usage and scenarios of lambda in nine shades and one depth, so-called nine shades and one depth, which means that 90% of the cases are used to create simple anonymous functions, and 10% of the cases are slightly more complicated (I'm too good at this excuse)
All in all is that there are two sides to everything, and we should stop and ask ourselves if we really need it before using lambda.
Of course, if you need to fool around with others are positive and negative a mouth, lambda is good or bad all depends on how we say, bragging please observe the following principles, tried and true:
If you say a college girl prostituting herself at night is shameful, but if you change it to a prostitute using her spare time to study hard is much more inspirational!
The same goes for lambda
apply function
The format of the apply function in Python is:apply(func,*args,**kwargs)
Of course, func can be an anonymous function.
Uses:Used to call a function indirectly when its arguments exist in a tuple or a dictionary, and to pass the arguments from the tuple or dictionary to the arguments in sequence
Parsing:args
is a tuple containing the positional parameters passed in accordance with the required parameters of the function, in short, if the function position of function A is A(a=1,b=2), then this tuple must be passed strictly in accordance with the positional order of the parameter (a=3,b=4), and can not be (b=4,a=3) in this order.kwargs
is a dictionary containing keyword arguments, and where args must be left empty in place of args if it is not passed and kwargs needs to be passed.
The return value of apply is the return value of the function func function.
Examples
def function(a,b): print(a,b) apply(function,('good','better')) apply(function,(2,3+6)) apply(function,('cai','quan')) apply(function,('cai',),{'b':'caiquan'}) apply(function,(),{'a':'caiquan','b':'Tom'})
Output results:
('good', 'better')
(2, 9)
('cai', 'quan')
('cai', 'caiquan')
('caiquan', 'Tom')
preprocessing of data, we use more is the apply function, apply function is a pandas library function, very good use of a functionEquivalent to the cycle of traversal, to the effect that each piece of data processing, function parameters may be DataFrame rows or columns.
Speaking of apply and have to say lambda functions, the combination of these two to use simply cool.
The lambda keyword can be used to create a small anonymous function
Example:
(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), *kwds)
The first parameter func is a function, you need to implement it yourself, you can use lambda anonymous function, axis default value is 0, axis is 0, it will be a column of data to traverse.
data[‘cut_review'].apply(lambda x: [i for i in x s if i not in stopwords])
⭐ The following example is the use of apply in DataFrame
# Function applications and mappings import numpy as np import pandas as pd df=((4,3),columns=list('bde'),index=['utah','ohio','texas','oregon']) print(df) """ b d e utah -0.667969 1.974801 0.738890 ohio -0.896774 -0.790914 0.474183 texas 0.043476 0.890176 -0.662676 oregon 0.701109 -2.238288 -0.154442 """ # Apply the function to a one-dimensional array of columns or rows. the DataFrame's apply method accomplishes this. f=lambda x:()-() # By default the function will be applied to columns individually as a unit of columns t1=(f) print(t1) t2=(f,axis=1) print(t2) """ b 1.597883 d 4.213089 e 1.401566 dtype: float64 utah 2.642770 ohio 1.370957 texas 1.552852 oregon 2.939397 dtype: float64 """ # In addition to scalars, the function passed to apply can also return a Series consisting of multiple values def f(x): return ([(),()],index=['min','max']) t3=(f) # As you can see from the results of the run, the results of the run of the calling function are appended on the right in the order of the column calls. print(t3) """ b d e min -0.896774 -2.238288 -0.662676 max 0.701109 1.974801 0.738890 """ #element-level python functions, applying functions to each element # Keep each floating point value in the DataFrame to two decimal places f=lambda x: '%.2f'%x t3=(f) print(t3) """ b d e utah -0.67 1.97 0.74 ohio -0.90 -0.79 0.47 texas 0.04 0.89 -0.66 oregon 0.70 -2.24 -0.15 """ #Note that map is used here because Series has a map method for element-level functions. And dataframe has only applymap. t4=df['e'].map(f) print(t4) """ utah 0.74 ohio 0.47 texas -0.66 oregon -0.15 """
to this article on the use of python3 apply function and lambda function details of the article is introduced to this, more related python3 apply function and lambda function content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!