我得到了一个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的一个相对较新的补充,因此关于如何使用它的指南还不多.