我得到了一大堆 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 的一個相對較新的補充,因此關于如何使用它的指南并不多。
uj5u.com熱心網友回復:
您可以使用警衛:
for event in data:
match event:
case {'id': x} if x.startswith("matchme"):
print(event["message"])
case {'id':'anotherid'}:
print(event["message"])
從檔案中參考,
警衛
我們可以在模式中添加一個 if 子句,稱為“守衛”。如果守衛為假,比賽繼續嘗試下一個案例塊。請注意,值捕獲發生在評估守衛之前:
match point: case Point(x, y) if x == y: print(f"The point is located on the diagonal Y=X at {x}.") case Point(x, y): print(f"Point is not on the diagonal.")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366626.html
標籤:Python json 蟒蛇-3.x 模式匹配 python-3.10
