简体   繁体   中英

Match case statement with multiple 'or' conditions in each case

Is there a way to assess whether a case statement variable is inside a particular list? Consider the following scenario. We have three lists.

a  = [1, 2, 3]
b  = [4, 5, 6]
c  = [7, 8, 9]

Then I want to check whether x is in each list. Something like that (of course this is a Syntax Error but I hope you get the point).

match x:
    case in a:
       return "132"
    case in b:
       return "564"
    case in c:
       return "798"

This can be easy with an if-else scenario. N.netheless, focusing on the match-case, if one has many lists. And big lists, it would be a mundane task to write them like that:

match x:
    case 1 | 2 | 3:
       return "132"
    case 4 | 5 | 6:
       return "564"
    case 7 | 8 | 9:
       return "762"

Is there an easy to way to check for multiple conditions for each case, without having to write them down?

I checked for duplicates, but I couldn't find them, I hope I don't miss something. Please be kind and let me know if there is a duplicate question.

As it seems case s accept a "guard" clause starting with Python 3.10 , which you can use for this purpose:

match x:
  case w if w in a:
    # this was the "case in a" in the question
  case w if w in b:
    # this was the "case in b" in the question
  ...

the w here actually captures the value of x , part of the syntax here too, but it's more useful in some other fancy cases listed on the linked whatsnew page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM