Python 3.10 pattern matching (PEP 634) - wildcard in string(Python 3.10模式匹配(PEP 634)-字符串中的通配符)
本文介绍了Python 3.10模式匹配(PEP 634)-字符串中的通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了一个很大的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的一个相对较新的添加,所以关于如何使用它的指南还不多。
推荐答案
您可以使用:
for event in data:
match event:
case {'id': x} if x.startswith("matchme"): # guard
print(event["message"])
case {'id':'anotherid'}:
print(event["message"])
引用自official documentation,
警卫
我们可以向模式添加
if子句,称为"警卫"。如果 卫士是false,匹配继续尝试下一个case挡路。请注意, 值捕获发生在评估保护之前: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.")
另请参阅:
- PEP 622 - Guards
- PEP 636 - Adding conditions to patterns
- PEP 634 - Guards
这篇关于Python 3.10模式匹配(PEP 634)-字符串中的通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:Python 3.10模式匹配(PEP 634)-字符串中的通配符
基础教程推荐
猜你喜欢
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
