如何在Python中匹配多个不同情况

huangapple go评论66阅读模式
英文:

How to match multiple different cases in Python

问题

使用match语句,可以为同一个case指定多个模式

match value:
   case 1 | 2 | 3:
     do_a()
   case 4:
     do_b()

我想要的是相反的,我想要匹配多个情况,每个情况都执行不同的代码,而只有一个值 - 我的想法是这样的

match value:
   case 1 | 2 | 3 | 'all':
     do_a()
   case 4 | 'all':
     do_b()
   case 'all':
     do_c()

如果value == 'all',我想同时运行do_a()do_b()do_c()。这可以轻松使用if-else实现,但我想利用更优雅的match语句。在其他具有switch的语言,如Java或C,我可以利用需要显式break的机制,让后续的情况在第一个匹配后执行。

在Python中,是否有一种机制可以处理这种用例(执行匹配相同值的多个块或'falling through'语句),还是我必须采用简单的条件?

目前,可行的版本是使用简单的if条件,我尝试了问题中描述的天真方法,但只有第一个匹配块会执行。

英文:

Using the match statement, one can specify multiple patterns for the same case\

match value:
   case 1 | 2 | 3:
     do_a()
   case 4:
     do(b)

What I want to do is the inverse, I want to match multiple cases, each of which executes a different code, with a single value - my idea was something like this

match value:
   case 1 | 2 | 3 | 'all':
     do_a()
   case 4 | 'all':
     do(b)
   case 'all':
     do(c)

I want to run both do_a(), do_b() and do_c() if value=='all'. This can be easily done with if-else, but I wanted to make use of the more elegant match statement. In other languages with switch, like Java or C, I could abuse the need for explicit break and let the subsequent cases be executed after the first match.

Is there a mechanism for this use-case in either fashion (executing multiple blocks with matching the same value or 'falling through' the statement) in python, or do I have to settle down for simple conditions?

Currently the working version is with simple if conditions, I've tried the naive approach described in the problem, but only the first match block executes.

答案1

得分: 1

我相信你能做到的最好是:

匹配值:
   情况 'all':
     做_a()
     做(b)
     做(c)
   情况 1 | 2 | 3:
     做_a()
   情况 4:
     做(b)

注意顺序。

英文:

I believe the best you can do is:

match value:
   case 'all':
     do_a()
     do(b)
     do(c)
   case 1 | 2 | 3:
     do_a()
   case 4:
     do(b)

Note the order.

huangapple
  • 本文由 发表于 2023年6月19日 17:09:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505183.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定