In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces what you should pay attention to when using Lambda in Python, it has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand it.
Lambda is considered to be a very Python language and one of the most popular features in Python programming. There are so many that many Python programmers want to use them as much as possible.
Of course, lambda has the advantage of making our code concise, but excessive use of them in a project can lead to abuse, making our code less readable and maintainable.
Before we start looking at what these misuses are, let's take a quick look at lambda. If you know them very well, you can skip to the next section.
Lambda, also known as the lambda function, is an anonymous function that can accept any number of parameters, but only one expression. Their declarations are represented by the lambda keyword. The basic syntax is as follows.
Lambda arguments: expression
Lambda is best suited for places where small features are needed and used only once. A common use of lambda is to set it as a key parameter in the built-in sorted () function. This is an example.
> students = [('Mike',' Mises, 15), ('Mary',' Mises, 14), ('David',' Mises, 16)] > sorted (students, key=lambda x: X [2]) [('Mary',' Falls, 14), ('Mike',' Mises, 15), ('David',' Mises, 16)] # The students are sorted by age
Many tutorials do a good job of explaining what lambda is and where lambda can be used, so there is no good reason to repeat a lot of it here.
Instead, the purpose of this article is to show you the most common misuses of lambda so that you may use them correctly when using lambda in situations other than those listed below.
1. Reinvent the wheel
The first misuse of lambdas is to ignore existing built-in functions.
Let's still take the sorted () function as an example. Suppose we have a list of strings and we want to sort them using their length.
Of course, the lambda function lambda x:len (x) works, but how about using the built-in len () function directly?
> pets = ['dog',' turtle', 'bird',' fish', 'kitty'] > sorted (pets, key=lambda x: len (x)) [' dog', 'bird',' fish', 'kitty',' turtle'] # The built-in len () function > > sorted (pets, key=len) ['dog',' bird', 'fish',' kitty', 'turtle']
This is another example that involves using the max () function.
> number_tuples = [(4,5,7), (3,1,2), (9,4,1)] > > sorted (number_tuples, key=lambda x: max (x)) [(3,1,2), (4,5,7), (9,4,1)] # The built-in max () function > > sorted (number_tuples, key=max) [(3,1,2), (4,5,7), (9,4,1)]
Good practice 1: think about built-in functions before writing your own Lambda.
two。 Assign it to a variable
In some tutorials (including some of my tutorials), I've seen how to assign lambdas to variables, but it mainly shows beginners that lambdas is essentially a function.
However, some beginners may have taken it as a good habit and thought that lambda is just a convenient way to declare short functions. The following code snippet shows you this abuse.
> divide_two_numbers = lambda x, y: X / y > divide_two_numbers (4,5) 0.8
Why should this be avoided? If you remember what was mentioned above, lambda should only be used once, so there is no reason to assign lambda to variables.
If you do need to use the relevant functionality, you should use the def keyword to declare a regular function, as shown below.
If you don't think the two lines of code that use this simple feature are cool, we can rewrite it as one line: defdivid_two_numbers_fun (xmemy): returns x / y, which works the same way.
> def divide_two_numbers_fun (XQuery y):... Return x / y... > > divide_two_numbers_fun (7,8) 0.875
The main reason to avoid assigning lambda to variables is for debugging / maintenance purposes, especially in a production / team environment.
Let's look at a simple example of what might happen. In practice, things may become much more complicated.
> > divide_two_numbers (3,0) Traceback (most recent call last): File ", line 1, in File", line 1, in ZeroDivisionError: division by zero > divide_two_numbers_fun (3,0) Traceback (most recent call last): File ", line 1, in File", line 1, in divide_two_numbers_fun ZeroDivisionError: division by zero
As you can see above, through the declaration of regular functions, we know exactly which function caused the error. By contrast, using lambda can only tell us that there is a lambda causing the error.
Why is the feature name not displayed?
This is because lambda is an anonymous function, and all these functions have the same name -. Can you imagine how frustrating it would be if your colleagues found dozens of errors?
Good practice 2: use regular functions instead of lambda multiple times.
3. Improper use of higher-order functions
When we talk about high-order functions, we mean functions that can operate on other functions by taking functions as arguments or by returning functions.
The functions related to the current topic are map (), filter (), and reduce (), which have been used more or less in many tutorials in lambda. However, this leads to some abuse of lambda and higher-order functions.
For demonstration purposes, I will only use the map () function in this tutorial, but the same principle applies to other higher-order functions.
Suppose we have a list of integers and want to have a list containing their squares. Lambda is used in conjunction with the map () function.
We will take a map object in the map () function, an iterator, and convert it to a list, on which we need to call the list () function.
> numbers = [1,2,3,5,8] > > squares = list (map (lambda x: X * x, numbers)) > squares [1,4,9,25,64]
In fact, the same function can be easily achieved through list understanding-without the need for higher-order functions or lambda. It's easier to read, isn't it?
Of course, mastering list comprehension is another "Pythonic feature" topic that requires another tutorial.
> numbers = [1,2,3,5,8] > > squares = [x * x for x in numbers] > squares [1,4,9,25,64]
Good practice 3: consider replacing higher-order functions with lambda with list derivation.
4. The expression is too clumsy
This is less common than the previous method. But some programmers just try to write the most Python code using lambda as much as possible. Sometimes there is a price to pay-readability.
Suppose we have a list of strings, and we need to sort them with a strange requirement: the number of different vowels in the word. Using lambda in the sorted () function is shown below.
> texts = ['iiiii',' bag', 'beto',' blackboard', 'sequoia'] > sorted (texts, key=lambda x: len (set ([l for l in list (x) if l in []) [' iiiii', 'bag',' beto', 'blackboard',' sequoia'])
It works as expected, but it's definitely not the easiest code to read. How about the following code?
> texts = ['iiiii',' bag', 'beto',' blackboard', 'sequoia'] > def number_distinct_vowels (x):. Vowels = ['await,' estranged, 'ified,' oiled,'u']... Vowels_only = [l for l in list (x) if l in vowels]... Distinct_vowels = set (all_vowels)... Return len (distinct_vowels)... > > sorted (texts, key=number_distinct_vowels) ['iiiii',' bag', 'beto',' blackboard', 'sequoia']
Of course, we need to write a few more lines of code, but isn't the new code more readable?
Good practice 4: if the expression of lambda is too cumbersome, write a regular function.
Thank you for reading this article carefully. I hope the article "what you should pay attention to when using Lambda in Python" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.