Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write the Lambda function of Python

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how to write a good Lambda function of Python, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Foreword:

The Lambda function is an anonymous function in Python. When you need to finish a small task, using them in the local environment can make the job easy. Some people call them lambdas for short, and their syntax is as follows:

Lambda arguments: expression

The lambda keyword can be used to create a lambda function, followed by a list of arguments and a single expression separated by colons. For example, lambda x: 2 * x is to multiply any input number by 2, while lambda x, y: X is the sum of two numbers. The grammar is very straightforward, isn't it?

Assuming you know what a lambda function is, this article aims to provide some general guidelines on how to use the lambda function correctly.

1. Do not return any value

If you look at the syntax, you may notice that we didn't return anything in the lambda function. This is all because the lambda function can contain only one expression. However, using the return keyword constitutes a statement that does not conform to the specified syntax, as follows:

> integers = [(3,-3), (2,3), (5,1), (- 4,4)] > > sorted (integers, key=lambda x: X [- 1]) [(3,-3), (5,1), (2,3), (- 4,4)] > > sorted (integers, key=lambda x: return x [- 1]). File "", line 1 sorted (integers, key=lambda x: return x [- 1]) ^ SyntaxError: invalid syntax

This error may be caused by an inability to distinguish between expressions and statements. Statements such as return, try, with, and if perform special actions. However, expressions refer to expressions that can be evaluated as a value, such as a numeric value or other Python object.

By using the lambda function, a single expression is evaluated as a value and participates in subsequent calculations, such as being sorted by the sorted function.

two。 Don't forget the better choice.

The most common use scenario for the lambda function is to use it as an argument to key in some built-in tool functions, such as sorted () and max () shown above. Depending on the situation, we can use other alternatives.

Consider the following example:

> > integers = [- 4,3,7,-5,-2,6] > > sorted (integers, key=lambda x: abs (x)) [- 2,3,-4,-5,6,7] > > sorted (integers, key=abs) [- 2,3,-4,-5,6,7] > > scores = [(93,100), (92,99), (95,94)] > > max (scores, key=lambda x: X [0] + x [1]) (93,100) > > max Key=sum) (93,100)

In the field of data science, many people use pandas libraries to process data. As shown below, we can use the lambda function to create new data from existing data through the map () function. In addition to using the lambda function, we can also use arithmetic functions directly, because pandas is supported:

> import pandas as pd > data = pd.Series ([1,2,3,4]) > data.map (lambda x: X + 5) 061 72 83 9dtype: int64 > data + 50 61 72 83 9dtype: int643. Do not assign it to a variable

I've seen some people mistake the lambda function for another declaration of a simple function, and we may have seen people do something like this:

> doubler = lambda x: 2 * x > doubler (5) 10 > doubler (7) 14 > type (doubler)

The only purpose of naming a lambda function may be for educational purposes to show that the lambda function is indeed the same function as any other function-- it can be called and has some function. Apart from that, we should not assign lambda functions to variables.

The problem with naming the lambda function is that it makes debugging less intuitive. Unlike other functions created using the regular def keyword, lambda functions have no name, which is why they are sometimes called anonymous functions. Consider the following simple examples to find out the subtle differences:

> inversive0 = lambda x: 1 / x > inversive0 (2) 0.5 > inversive0 (0) Traceback (most recent call last): File ", line 1, in File", line 1, in ZeroDivisionError: division by zero > def inversive1 (x):. Return 1 / x... > inversive1 (2) 0.5 > inversive1 (0) Traceback (most recent call last): File ", line 1, in File", line 2, in inversive1ZeroDivisionError: division by zero

When there is a problem with the lambda function in our code (that is, inversive0), the Traceback error message will only prompt you that there is a problem with the lambda function.

By contrast, using normally defined functions, Traceback clearly prompts you for problematic functions (that is, inversive1).

Related to this, if you want to use the lambda function multiple times, the best practice is to use regular functions defined through def that allow the use of document strings.

4. Don't forget the list derivation.

Some people like to use lambda functions with higher-order functions, such as map or filter. Consider the following usage example:

> # create a list of numbers > numbers = [2, 1, 3] > # use map function with lambda function > list (map (lambda x: X * x, numbers)) [4,1,9,9] > # use filter function with lambda function > list (filter (lambda x: x% 2, numbers)) [1,3,-3]

We can use a more readable list derivation instead of the lambda function. As shown below, we use list deduction to create the same list object. As you can see, it was more troublesome to use the map or filter function with the lambda function than the list derivation. Therefore, you should consider using list deductions when creating lists that involve higher-order functions.

> # Use list comprehensions > [x * x for x in numbers] [4,1,9,9] > [x for x in numbers if x% 2] [1,3,-3] these are all the contents of this article "how to write the Lambda function of Python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report