Table of contents
Author:qyan.li
Date:2022.4.28
Topic: lambda expression, list generation, map function introduction and usage analysis
Reference: https://zhuanlan.zhihu.com/p/163065966 , https://zhuanlan.zhihu.com/p/163065966
One, written in front:
~~~~~~ Recently, QT
when creating a learning interface, the internal parameters Button
of some components (such as ) sometimes need to pass in expression-assisted functions, so the system understands the basic usage of lambda expressions, and introduces the other two commonly used techniques.connect
lambda
2. lambda
Expression:
~~~~~~ lambda
Expressions can be summed up in one sentence: a convenient definition and expression of simple functions that support parameter passing .
~~~~~~ It can be explained in a more detailed language: lambda
expressions can simplify the difficulty of writing simple functions, and realize the definition and use of functions in a relatively convenient way. Of course, this is just my own simple way of understanding, but lambda
it is sufficient for most expression scenarios.
Here are a few simple chestnuts for everyone to understand:
func = lambda x,y : x+y
func(1,2)
~~~~~~ Let me explain, the name of this function is func
, when receiving two parameters x,y
, the operation completed inside the function is x+y
, compared to the complicated function definition, this method is obviously simpler.
def func(x,y):
return x + y
~~~~~~ Of course, if everyone intends, it is also completely combined with other basic grammars, such as if else
or for
loops, and I will also give a chestnut to explain:
func = lambda x,y : x+y if x > 0 and y < 0 else None
func(1,-6)
~~~~~~ The above code snippet shows the combination of lambda
expressions and examples. The example of combining expressions and loops is not shown here. If you are interested, you can refer to the link in , which has an introduction.if else
lambda
for
Reference
~~~~~~ The reason not introduced here is also mentioned in the reference blog post, because it is not recommended for everyone to use, because the combination of lambda
expressions and for
loops may greatly reduce the readability of the code, but lambda
the purpose of our use of expressions is to Simplify the code, if the acquisition of simplicity is at the expense of code readability, the gain is not worth the loss.
Three, list generation:
~~~~~~ The above introduction mentioned that the combination of lambda
expressions and for
loops is not recommended, but we do need to simplify the use of for loops in some scenarios, such as the need to generate a list of squares of 1-100 numbers:
Assuming a conventional for
loop:
lst = []
for i in range(1,101):
lst.append(i**2)
~~~~~~ However, assuming the help of list comprehensions, the code becomes like this:
lst = [i**2 for i in range(1,101)]
~~~~~~ Obviously, compared with the two pieces of code, the latter code is much simplified. Therefore, in some scenarios, the advantage of list generation is still obvious. Of course, it can also be used in conjunction with if judgment or function:
## 列表生成式结合if判断
lst = [i**2 for i in range(1,101) if i%2 == 0]
## 列表生成式结合函数
def isPremier(num):
if num < 2:
return -1
else:
for i in range(2,num):
if num%i == 0:
return 0
else:
continue
return num
PremireLst = [num for num in range(2,101) if isPremier(num) != 0]
print(PremireLst)
~~~~~~ Written here, the basic usage of the list generation formula has been explained, let’s make a small summary:
List generation, simply speaking, is a concise way to generate lists, which can be if else
combined with functions to simplify generation operations
4. map()
Function usage:
~~~~~~ map()
Why are functions mentioned here ? Because map()
the use of functions is generally lambda
combined with expressions, the functions are mentioned here map()
.
~~~~~~ First of all, let's look at a simple chestnut to convert the strings in the list to uppercase strings:
## 借助于map函数和lambda表达式
lst = list(map(lambda x : x.upper(),["beijing","shanghai","gaungzhou"]))
lst
~~~~~~ With the help of the above code, the given requirement can be realized, and the code can be simplified at the same time. Seeing that some students here may think, it seems that using the list generation method is also possible, or even simpler:
lst = [x.upper() for x in ["beijing","shanghai","gaungzhou"]]
~~~~~~ So, what is the difference between the two? This requires understanding the function and usage of the map function:
~~~~~~ map()
Personally, the function is a mapping function, and the parameters are passed in internally (func,iterable)
. These two parameters are necessary, and their functions are to func
define iterable
the operation performed on each element in the object, and iterable
define the target object of the operation. iterable
The object can be used ( python
inside built types list,tuple,dict
) are iterable.
~~~~~~ After reading the above description, you will find that map()
the function of the function is essentially similar to the list generation. Moreover, from the perspective of practical application, the effect is indeed similar. But it may be relatively speaking, map()
the function is more standardized, and the iteration objects are more diversified, and there are relatively more transformations that can be performed. Therefore, when you read some algorithms, you will AI
find that you like to use map
functions very much.
remind some small
Tips:
- The list generation must be added on the left and right sides
[]
, otherwise an error will be reportedmap()
python2.0
The return value of the function inlist
the type, butpython3.0
the return value in themap
V. Summary:
lambda
Expressions, list generators,map()
and functions are all designed to simplify the complexity of the code, but they must not be at the expense of the readability of the code- In practical applications,
lambda+map
it is similar to the list generation formula, butlambda+map
its ability and breadth to deal with problems are greater than that of the list generation formula
Sixth, write at the end:
~~~~~~ At the end of the article, I suddenly thought of a question. The original purpose of understanding these is to solve QT
the problems encountered in the article, so I will briefly talk about this question at the end:
~~~~~~ As usual, let’s look at the code first:
## 使用lambda表达式(传入函数名称+参数)
button1.clicked.connect(lambda: self.onClicked(button1))
def onClicked(self, button):
print("Button {0} is clicked.".format(button.text()))
## 直接传入参数名称
button.clicked.connect(self.onOKClicked)
def onOKClicked(self):
items = ["C++", "Python", "Java", "Go"]
item, ok = QInputDialog.getItem(self, "Select an Item", "Programing Language", items, 1, True)
if ok and item:
print("selected item: ", item)
~~~~~~ It is difficult to read the code content, which is not a big problem. We only need to compare the connect
gap between the parameters passed in the two functions. It can be seen that the first one uses the lambda
expression to pass in the parameters, and the second one directly passes in the function name , which provides us with another practical application scenario of lambda expressions: when a function is passed in as a parameter and needs to carry parameters , the expression can be used lambda
. Although I don't know whether this summary is scientific, the above example does provide Another direction and application.