我有一个很大的 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"
}, ...]
Run Code Online (Sandbox Code Playgroud)
我想做一些可以匹配 id 的事情,而不必制作一长串|'s。
像这样的东西:
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'])
Run Code Online (Sandbox Code Playgroud)
它是 Python 的一个相对较新的补充,因此目前还没有太多关于如何使用它的指南。