代码之家  ›  专栏  ›  技术社区  ›  ideasman42

在结构模式匹配的默认情况下,如何访问匹配的值?

  •  1
  • ideasman42  · 技术社区  · 3 年前

    使用Python3.10的match语句,是否可以使用默认情况下满足的值?

    还是需要先给它分配一个变量 match 那么它可以在默认情况下使用?

    match expensive_calculation(argument):
        case 'APPLE':
            value = 'FOO'
        case 'ORANGE':
            value = 'BAR'
        case _:
            raise Exception(
               "Wrong kind of fruit found: " +
               str(expensive_calculation(argument))
               # ^ is it possible to get the default value in this case?
            )
    
    1 回复  |  直到 3 年前
        1
  •  2
  •   Ajax1234    3 年前

    你可以使用 as pattern :

    match expensive_calculation(argument):
      case 'APPLE':
        value = 'FOO'
      case 'ORANGE':
        value = 'BAR'
      case _ as argument: #here, using `as` to save the wildcard default to `argument`
        raise Exception(f"Wrong kind of fruit found: {str(argument)}")