我得到了一大堆 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 的事情,而不必制作一长串的|
'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'])
它是 Python 的一个相对较新的补充,因此关于如何使用它的指南并不多。