Detailed explanation of basic usage of lambda expression, list generation, and map() function in python


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, QTwhen creating a learning interface, the internal parameters Buttonof 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.connectlambda

2. lambdaExpression:

       ~~~~~~       lambdaExpressions 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: lambdaexpressions 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 lambdait 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 elseor forloops, 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 lambdaexpressions 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 elselambdaforReference

       ~~~~~~       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 lambdaexpressions and forloops may greatly reduce the readability of the code, but lambdathe 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 lambdaexpressions and forloops 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 forloop:

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 elsecombined with functions to simplify generation operations

4. map()Function usage:

       ~~~~~~       map()Why are functions mentioned here ? Because map()the use of functions is generally lambdacombined 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 funcdefine iterablethe operation performed on each element in the object, and iterabledefine the target object of the operation. iterableThe object can be used ( pythoninside 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 AIfind that you like to use mapfunctions very much.

remind some smallTips:

  1. The list generation must be added on the left and right sides [], otherwise an error will be reported
  2. map()python2.0The return value of the function in listthe type, but python3.0the return value in themap

V. Summary:

  1. lambdaExpressions, 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
  2. In practical applications, lambda+mapit is similar to the list generation formula, but lambda+mapits 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 QTthe 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 connectgap between the parameters passed in the two functions. It can be seen that the first one uses the lambdaexpression 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.

Guess you like

Origin blog.csdn.net/DALEONE/article/details/124509778
Recommended