我有一个大的JSON对象列表,我想根据其中一个键的开头进行解析,并仅使用通配符匹配其余部分。 许多键都很相似,例如“matchme-foo”和“matchme-bar”。 有一个内置通配符,但它仅用于整个值,有点像“else”。 我可能会忽视某些事情,但我无法在建议书中找到任何解决方案:https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching 此外,在PEP-636中还有更多相关信息:https://www.python.org/dev/peps/pep-0636/#going-to-the-cloud-mappings 我的数据看起来像这样:
data = [{
"id" : "matchme-foo",
"message": "hallo this is a message",
},{
"id" : "matchme-bar",
"message": "goodbye",
},{
"id" : "anotherid",
"message": "completely diffrent event"
}, ...]
我希望能够做一些事情,可以匹配id而不必制作一长串的|
。
就像这样:
for event in data:
match event:
case {'id':'matchme-*'}: # Match all 'matchme-' no matter what comes next
log.INFO(event['message'])
case {'id':'anotherid'}:
log.ERROR(event['message'])
它是Python相对较新的补充,因此还没有很多关于如何使用它的指南。