简体   繁体   中英

python structural pattern matching for string containing float

How can I use structural pattern matching for the following use case:

values = ["done 0.0", "done 3.9", "failed system busy"]

for v in values:
   vms = v.split()
   match vms:
       case ['done', float()>0]: # Syntax error
           print("Well done")
       case ['done', float()==0]: # Syntax error
           print("It is okay")
       case ['failed', *rest]:
           print(v)

Please excuse me for the syntax errors, I have written this to demonstrate my thought process.

What could be the right syntax to achieve this pattern matching? Is it even possible?

if...else would be simpler but if you do want pattern matching then you have a number of issues to be resolved. Your string does not contain a float, it contains a string of characters which could be converted to a float. So to test value of a float you have to test that it IS a float in string form and then convert to a float then test. The 'wildcard' character is _ which should be used to capture non-matching elements. The following code does what I think you want and could be the basis for further development. Regex is used to test for the float with a 'guard' expression in the pattern. The Regex would pick up error entries such as "3.x".

import re
values = ["done 0.0", "done 3.9", "failed system busy"]

for v in values:
    vms = v.split()
 
    match vms:
        case ['done', x] if x == '0.0': print(vms, 'It is OK')
        case ['done', x] if re.match(r'\d+.\d+', x) and float(x) > 3.0: print(vms, 'Well done')
        case ['failed', _,_]: print(v)
        case _: print('unknown case')

produces:

['done', '0.0'] It is OK
['done', '3.9'] Well done
failed system busy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM