In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how to use walrus operators to reduce repetitive code in Python. I think it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.
A = b is a common assignment statement, which is read as an equals b, while a: = b is an assignment expression, which is read as a walrus b. Why is this symbol called walrus? Because after turning: = clockwise 90 °, the colon is the walrus's eyes, and the equal sign is its tusks.
This kind of expression is very useful and can be used in situations where ordinary assignment statements cannot be applied, such as in if statements of conditional expressions. The value of the assignment expression is the value assigned to the identifier to the left of the walrus operator.
For instance. If there is a basket of fresh fruit to make ingredients for the juice shop, then we can define the content as follows:
Fresh_fruit = {'apple': 10,' banana': 8, 'lemon': 5,}
Before customers order lemon juice, we have to make sure that there are still any lemons to squeeze. Therefore, first find out the number of lemons, and then use the if statement to determine whether it is a non-zero value.
Def make_lemonade (count): print (f'Making {count} lemons into lemonade') def out_of_stock (): print ('Out of stockholders') Count = fresh_fruit.get ('lemon', 0) if count: make_lemonade (count) else: out_of_stock ()
Although this code looks simple, it is a bit loose, because although the count variable is defined on top of the entire if/else structure, it is only used by the if statement, and the else block does not need to use this variable at all. Therefore, this way of writing misleads people into thinking that count is an important variable and that both if and else use it, but this is not the case.
In Python, we often have to get a value first, then determine whether it is non-zero, and if so, execute a piece of code. For this usage, we used to use a variety of techniques to avoid repeated variables such as count in the code, which sometimes make the code more difficult to understand. Python introduces assignment expressions to solve this problem. Here is the walrus operator instead:
If count: = fresh_fruit.get ('lemon', 0): make_lemonade (count) else: out_of_stock ()
Although the new code saves only one line, it is much clearer to read, because this writing clearly shows that the count variable is only related to the if block. This assignment expression first assigns the value on the right side of: = to the count variable on the left, and then evaluates itself, that is, treating the value of the variable as the value of the entire expression.
Because the expression follows if, the program decides whether the if block should be executed based on whether its value is non-zero. This practice of assigning a value before judging is exactly what the walrus operator is trying to express.
Lemon juice is powerful, so only one lemon is needed to complete the order, which means the program only needs to judge whether it is non-zero. If the guest orders apple juice, you have to use at least four apples. According to the traditional way of writing, it is necessary to first look up the number of apple (count) in the dictionary fresh_fruit, and then construct a conditional expression (count > = 4) based on this number in the if statement.
Def make_cider (count): print (f'Making cider with {count} apples') count = fresh_fruit.get ('apple', 0) if count > = 4: make_cider (count) else: out_of_stock ()
This code, like the lemon juice example, overemphasizes the meaning of the count variable. Let's use the walrus operator to write the code more clearly.
If (count: = fresh_fruit.get ('apple', 0)) > = 4: make_cider (count) else: out_of_stock ()
As in the previous example, the modified code is one line less than the original. But this time, we should also pay attention to another phenomenon: the assignment expression itself is placed in a pair of parentheses. Why would you do that? Because we want to compare the result of this expression with the value of 4 in the if statement.
There are no parentheses in the lemon juice example, because at that time the direction of the if/else can be determined by the value of the assignment expression itself: as long as the value of the expression is not 0, the program enters the if branch. But not this time, this time to put the assignment expression in a larger expression, so you have to enclose it in parentheses. Of course, when it is not necessary to add parentheses, it is better to try not to add parentheses.
There is a similar logic that repeats the code just mentioned, which means that we assign a different value to a variable according to the situation, and then use that variable as an argument to call a function.
For example, if a customer orders a banana smoothie, we first have to cut the banana into several pieces, and then use two of them to make the smoothie. If there are not enough bananas, throw an OutOfBananas exception. Let's use the traditional writing method to implement this logic:
Def slice_bananas (count): print (f'Slicing {count} bananas') return count * 4 class OutOfBananas (Exception): pass def make_smoothies (count): print (f'Making a smoothies with {count} banana slices') pieces = 0 count = fresh_fruit.get ('banana', 0) if count > = 2: pieces = slice_bananas (count) try: smoothies = make_smoothies (pieces) except OutOfBananas: out_of_stock ()
Another traditional way of writing is to move the assignment statement pieces = 0 at the top of the if/else structure to the else block.
Count = fresh_fruit.get ('banana', 0) if count > = 2: pieces = slice_bananas (count) else: pieces = 0 try: smoothies = make_smoothies (pieces) except OutOfBananas: out_of_stock ()
This kind of writing looks a little strange because both the if and else branches define initial values for the pieces variable. According to the scope rules of Python, this method of defining the initial values of variables separately is valid. Although it is true, it looks awkward to write this way, so many people like to use the first way to write, that is, to set the initial value of pieces before entering the if/else structure.
By using the walrus operator instead, you can write one less line of code and depress the status of the count variable so that it appears only in the if block, so that we can more clearly realize that the pieces variable is the focus of the whole code.
Pieces = 0 if (count: = fresh_fruit.get ('banana', 0)) > = 2: pieces = slice_bananas (count) try: smoothies = make_smoothies (pieces) except OutOfBananas: out_of_stock ()
For the writing of defining pieces variables in the if and else branches respectively, the walrus operator can also make the code clear because this time there is no need to put the count variable on top of the entire if/else block.
If (count: = fresh_fruit.get ('banana', 0)) > = 2: pieces = slice_bananas (count) else: pieces = 0 try: smoothies = make_smoothies (pieces) except OutOfBananas: out_of_stock ()
Novices to Python often encounter the difficulty of not finding a good way to implement switch/case structures. The closest approach to this structure is to continue to nest if/else structures within the if/else structure, or to use the if/elif/else structure.
For example, we want to automatically make drinks for our guests in a certain order, so that we don't have to order. The following logic first determines whether you can make banana smoothies, if not, make apple juice, and if not, make lemon juice:
Count = fresh_fruit.get ('banana', 0) if count > = 2: pieces = slice_bananas (count) to_enjoy = make_smoothies (pieces) else: count = fresh_fruit.get (' apple', 0) if count > = 4: to_enjoy = make_cider (count) else: count = fresh_fruit.get ('lemon' 0) if count: to_enjoy = make_lemonade (count) else: to_enjoy = 'Nothing'
This ugly way of writing is actually very common in Python code. Fortunately, we now have the walrus operator, which allows us to easily simulate a scheme that is very close to switch/case.
If (count: = fresh_fruit.get ('banana', 0)) > = 2: pieces = slice_bananas (count) to_enjoy = make_smoothies (pieces) elif (count: = fresh_fruit.get (' apple', 0)) > = 4: to_enjoy = make_cider (count) elif count: = fresh_fruit.get ('lemon', 0): to_enjoy = make_lemonade (count) else: to_enjoy =' Nothing'
This version is only five lines shorter than the original, but it looks much clearer because the nesting depth and indentation levels are reduced. As long as we encounter the ugly structure just now, we should consider whether we can use the walrus operator instead.
Another difficulty new to Python is the lack of a do/while loop structure. For example, we should make juice from the new fruit and put it in a bottle until the fruit is used up. Let's start with a normal while loop:
FRUIT_TO_PICK = [{'apple': 1,' banana': 3}, {'lemon': 2,' lime': 5}, {'orange': 3,' melon': 2},] def pick_fruit (): if FRUIT_TO_PICK: return FRUIT_TO_PICK.pop (0) else: return [] def make_juice (fruit, count): return [(fruit) Count)] bottles = [] fresh_fruit = pick_fruit () while fresh_fruit: for fruit, count in fresh_fruit.items (): batch = make_juice (fruit, count) bottles.extend (batch) fresh_fruit = pick_fruit () print (bottles)
In this way, fresh_fruit = pick_fruit () must be written twice, first before entering the while loop, because we have to set the initial value for fresh_fruit, and the second time is at the end of the body of the while loop, because we have to fill the fresh_fruit with the list of fruits to be processed in the next round.
If you want to reuse this line of code, consider the loop-and-a-half pattern. This pattern eliminates repetition, but it makes the while loop look stupid because it becomes an infinite loop that the program can only jump out of with break statements.
FRUIT_TO_PICK = [{'apple': 1,' banana': 3}, {'lemon': 2,' lime': 5}, {'orange': 3,' melon': 2},] bottles = [] while True: # Loop fresh_fruit = pick_fruit () if not fresh_fruit: # And a half break for fruit Count in fresh_fruit.items (): batch = make_juice (fruit, count) bottles.extend (batch) print (bottles)
With the walrus operator, there is no need to use the loop-and-a-half mode, we can assign a value to the fresh_fruit variable at the beginning of each loop and decide whether to continue the loop based on the value of the variable. This method of writing is easy to read, so it should be the first choice.
FRUIT_TO_PICK = [{'apple': 1,' banana': 3}, {'lemon': 2,' lime': 5}, {'orange': 3,' melon': 2},] bottles = [] while fresh_fruit: = pick_fruit (): for fruit, count in fresh_fruit.items (): batch = make_juice (fruit, count) bottles.extend (batch) print (bottles)
In other cases, assignment expressions can also reduce repetitive code. In short, if an expression or assignment occurs multiple times in a set of code, consider using an assignment expression to make the code simpler.
Keystone
The assignment expression assigns a value to the variable through the walrus operator (: =) and makes the value the result of this expression, so we can use this feature to reduce the code.
If the assignment expression is part of a large expression, you have to enclose it in a pair of parentheses.
Although Python does not support switch/case and do/while structures, this logic can be clearly simulated using assignment expressions.
This is how to use walrus operators in Python to reduce repetitive code. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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.
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.