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 

wildcard

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 

summary

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 !

copyright notice
author[Blind brother Python],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201302119448549.html

Random recommended