繁体   English   中英

python 包含浮点数的字符串的结构模式匹配

[英]python structural pattern matching for string containing float

如何为以下用例使用结构模式匹配:

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)

请原谅我的语法错误,我写这篇文章是为了展示我的思维过程。

实现这种模式匹配的正确语法是什么? 有可能吗?

if...else会更简单,但如果您确实想要模式匹配,那么您有许多问题需要解决。 您的字符串不包含浮点数,它包含一串可以转换为浮点数的字符。 因此,要测试浮点数的值,您必须测试它是字符串形式的浮点数,然后转换为浮点数然后进行测试。 “通配符”字符是_ ,应该用于捕获不匹配的元素。 下面的代码做我认为你想要的,可以作为进一步开发的基础。 正则表达式用于测试模式中带有“guard”表达式的浮点数。 正则表达式会选择错误条目,例如“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')

产生:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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