current position：Home>New statement match, the new version of Python is finally going to introduce switch case?
New statement match, the new version of Python is finally going to introduce switch case?
2022-01-30 21:19:49 【Blind brother Python】
match sentence (python3.10)
In many languages , There is a method for conditional judgment switch-case sentence , But in python All the time , No, switch-case. But in the python3.10 In the new version of , Joined the match-case sentence .
match The basic usage of the statement is the same as switch-case The statement is similar to , It's through match and case The combination of , Complete structured pattern matching . however match Statement is not equivalent to switch-case, because match Statement has some other functions available .
Another thing to note , Although as of the current version (2021 year 11 month ),match and case Has not been officially added to the keyword list , That is to say, at present, you can still match and case As a variable , Function name, etc , But it is expected that in the near future ,match and case May be added to the keyword list .
Basic usage ： Matching literal values
If you have ever learned or used switch sentence , So you should be right match The basic usage of does not feel strange . But here's the thing , stay python in , There has always been an indentation requirement , stay case It needs to be indented once , stay case Inside , You need to indent again . In addition to switch-case The difference is ,python Not required in break Jump out of the statement , Once you have match The match is successful , Will end the statement . besides , And added _ wildcard , As if none of the previous matches succeed , To perform the case To use .
a = 520 match a: case 314: print("314") case 520: print("520") case 1314: print("1314") case _: print(" nothing in the world ") Copy code
The result of the above code is , Print 520. Because of the variable a stay case 520 Match succeeded , therefore , Execute the contents of this code , And end . Although not used break, But not with swtich-case equally , So let's keep going .
If , You have to match multiple literal values at the same time , Can pass | Connect , It plays a role equivalent to "or", But it doesn't work or Instead of |.
case 520 | 1314: print("5201314") Copy code
If more than one case All options can be matched successfully , Then only the first successful match will be executed case Code segment , Follow up can match successful case It will not be run .
In addition to python in ,case There is no limit to what matches , Floating point numbers , Lists and so on can also be put in to match . But here's the thing , The list must have the same order of elements , To match success , But there is no such requirement in the dictionary , No matter what order the key values are added , It doesn't affect the matching results .
Special Usage ： Bound variable
If in match Of the statement case in , The variable... Appears ( Or identifier ), that , This variable will match as much as possible match The content of , And assigned .
a = 520 match a: case b: print("520") print(b) # here b As the result of the 520, No matter what b Has it ever been defined before Copy code
The above code uses a variable name that doesn't exist at all b To match a, The result is a successful match , also b Assigned to a Value .
Of course , If that's all , Then we can't directly see the meaning of use , therefore , Its value lies in , It can be similar to unpacking , To match a list or tuple .
a = [520, 1314] match a: case [1314, b]: print(1) case [520, c]: print(2) # After this code runs , prints 2 # because [1314, b] Unable to join [520, 1314] The match is successful # therefore [520, c] The match is successful ,c To be an assignment 1314 Copy code
Speaking of lists and tuples , One more thing we need to mention is , In the current match In the matching of statements , Do not distinguish between lists and tuples , They are the same in matching .
a = [520, 1314] match a: case (520, 1314): print(" Can be matched successfully ") a = (520, 1314) match a: case [520, 1314]: print(" This can also be matched successfully ") Copy code
Before , We have already introduced ,match The statement uses a single underscore _ As a wildcard , The function used alone is similar to switch-case Statement default, But actually , Wildcards can not only be used alone at the end of a statement , It can also be used as a wildcard in combination , Participate in unpacking .
a = [520, 1314] _ = 12 match a: case [1314, _]: print(1) case [520, _]: print(2) case _: print(3) # The execution result of the above code is , Print 2, because [520, _] Matched successfully # It is worth noting that , Now the variable _ The print result of is still 12 # Because the parameters match _ The wildcard _, It is not the variables mentioned in the previous special pattern that participate in the matching # therefore , The final result of successful matching , It will not be assigned to a variable with the same name _ print(_) Copy code
Guard item (if conditional )
stay case In , We can join a if Conditional judgment as a guard item . If if If conditional judgment fails , Then the case Statement will not be used , Keep looking for the next case. The use method is similar to that in the list derivation , Add one if.
a = [520, 1314] match a: case [x, y] if x > y: print("x > y") case [x, y] if x < y: print("x < y") # The running result of the above code is ,x < y Copy code
Be careful :case Matching and case in if The trigger time of judgment is , Match first , Then start again if Judge . therefore , Although variable x and y None of them ever showed up , But don't worry , Because when x,y After the match is successful , Will go to if Judge , At this time x and y It has been assigned , Can be compared , There will be no undefined variables .
This match and if The order of judgment means , Even if if Judgment failed , As long as the match can succeed , The variable will still be assigned .
a = [520, 1314] match a: case [x, y] if x > y: print(" This code will not be printed ") print(x, y) # here x by 520,y by 1314 # although if Judgment failed ,case The content in is not executed # But because of case Match before if The judgment is successful , So the variable x and y The assignment has been completed Copy code
1,match The basic functions and functions of the statement switch-case similar , Can complete the condition judgment , however match Statements are more powerful , Variable types are not restricted in matching .
2,match Statement execution completes the first successful match case The paragraph will end after , Will not continue to look for the next case, There is no need to use it manually break.
3,match There is no use of default, Instead, wildcards are selected _, Can pass case _ Placing at the end means that the match can be successful at any time , You can also use wildcards _ For unpacking .
4,match Statement can perform functions similar to unpacking , As long as case Use variables in , Will match as much as possible , And assign values to variables .
5,match You can add... To the statement if Judgment as a guardian , But here's the thing ,case The matching trigger time is earlier than if Judge . So as long as the match can succeed , Even if if Fail to judge , The variable will still be assigned .
Last , I'm blind brother , Focus on python Study , Like it , Please pay attention to me. , Your support for me , It's really important ！
author[Blind brother Python],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Introduction to python (IV) dynamic web page analysis and capture
- leetcode 119. Pascal's Triangle II（python）
- leetcode 31. Next Permutation（python）
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat 
guess what you like
This is what you should do to quickly create a list in Python
On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
Python OpenCV image area contour mark, which can be used to frame various small notes
How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
Initial Python tuple
Introduction to Python urllib module
Advanced Python Basics: from functions to advanced magic methods
Python Foundation: data structure summary
Python Basics: from variables to exception handling
Python notes (22): time module and calendar module
- Python notes (20): built in high-order functions
- Python notes (17): closure
- Python notes (18): decorator
- Python notes (16): generators and iterators
- Python notes (XV): List derivation
- Python tells you what timing attacks are
- Python -- file and exception
- [Python from introduction to mastery] (IV) what are the built-in data types of Python? Figure out
- Python code to scan code to pay attention to official account login
- [algorithm learning] 1221 Split balanced string (Java / C / C + + / Python / go / trust)
- Python notes (22): errors and exceptions
- Python has been hidden for ten years, and once image recognition is heard all over the world
- Python notes (21): random number module
- Python notes (19): anonymous functions
- Use Python and OpenCV to calculate and draw two-dimensional histogram
- Python, Hough circle transformation in opencv
- A library for reading and writing markdown in Python: mdutils
- Datetime of Python time operation (Part I)
- The most useful decorator in the python standard library
- Python iterators and generators
- [Python from introduction to mastery] (V) Python's built-in data types - sequences and strings. They have no girlfriend, not a nanny, and can only be used as dry goods
- Does Python have a, = operator?
- Go through the string common sense in Python
- Fanwai 4 Handling of mouse events and solutions to common problems in Python opencv
- Summary of common functions for processing strings in Python
- When writing Python scripts, be sure to add this
- Python web crawler - Fundamentals (1)
- Pandas handles duplicate values
- Python notes (23): regular module
- Python crawlers are slow? Concurrent programming to understand it
- Parameter passing of Python function
- Stroke tuple in Python
- Talk about ordinary functions and higher-order functions in Python
- [Python data acquisition] page image crawling and saving
- [Python data collection] selenium automated test framework
- Talk about function passing and other supplements in Python
- Python programming simulation poker game
- leetcode 160. Intersection of Two Linked Lists （python）
- Python crawler actual combat, requests module, python to grab the beautiful wallpaper of a station
- Fanwai 5 Detailed description of slider in Python opencv and solutions to common problems