英文:
How to combine two match patterns with guards in Python
问题
考虑以下情况:
匹配 var1:
如果 var2 == 1 的话,情况 enum.A:
{代码块}
如果 var2 == 2 的话,情况 enum.B:
{代码块}
...
这里的 {代码块}
是完全相同的代码,我不想重复。
有没有一种好的方法可以在不将 {代码块}
重构为函数的情况下进行穿透或组合这两种情况?
英文:
Consider the following case:
match var1:
case enum.A if var2 == 1:
{code block}
case enum.B if var2 == 2:
{code block}
...
Here {code block}
is exactly the same code, which I don't want to repeat.
Is there a nice way of doing a fall-through or combining these two cases without refactoring {code block}
into a function?
答案1
得分: 2
使用组合的子模式在枚举值上:
示例:
from enum import Enum
class E(Enum):
A = 'A'
B = 'B'
v1 = 'B'
v2 = 3
match (v1, v2):
case (E.A.value, 1) | (E.B.value, (2 | 3 | 4 | 5)):
print('ok')
case _:
print('pass')
ok
英文:
Use combined sub-patterns on enum value
s:
Sample:
from enum import Enum
class E(Enum):
A = 'A'
B = 'B'
v1 = 'B'
v2 = 3
match (v1, v2):
case (E.A.value, 1) | (E.B.value, (2 | 3 | 4 | 5)):
print('ok')
case _:
print('pass')
ok
答案2
得分: 1
你可以通过匹配元组来获得所需的效果:
match (var1, var2):
case (enum.A, 1) | (enum.B, 2):
{代码块}
...
在评论中,你还提到:
> 如果第二个 case 是 case enum.B if var2 in {2, 3, 4, 5}:
怎么办?
在这种情况下,你可以使用嵌套模式,类似于 PEP 636 中示例所示的方式:
match (var1, var2):
case (enum.A, 1) | (enum.B, (2 | 3 | 4 | 5)):
{代码块}
...
(感谢 RomanPerekhrest 的回答,我之前不知道这个。)
英文:
You can get the desired effect by matching on tuples:
match (var1, var2):
case (enum.A, 1) | (enum.B, 2):
{code block}
...
In a comment you additionally asked:
> What if the second case is case enum.B if var2 in {2, 3, 4, 5}:
?
In this case you may use a nested pattern, analogous to the example shown in PEP 636:
match (var1, var2):
case (enum.A, 1) | (enum.B, (2 | 3 | 4 | 5)):
{code block}
...
(Credits go to RomanPerekhrest's answer, I did not know this before.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论