如何在以下用例中使用结构模式匹配:
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
另一种没有正则表达式的方法是编写一个检查函数,例如:
def check_float(f):
f = f.strip()
try:
_ = float(f)
except:
return False
return True
那么情况就是:
case ['done', x] if check_float(x) and float(x) > 3.0: print(vms, 'Well done')
values = ['done 0.0', 'done 3.9', 'failed system busy']
for v in values:
match v.split():
case 'done', x if float(x) > 0:
print('Well done')
case 'done', x if float(x) == 0:
print('It is okay')
case 'failed', *rest:
print(v)
此外,您可能需要添加最后一个案例来捕获未涵盖的案例:
case _:
print('Any other case')
这比
ìf-then-else-try-catch
替代方案更清晰、更简洁。实际上,
match
就是为了这种情况而创建的。这就是为什么它被称为结构模式匹配。