如何在结构模式匹配的默认情况下访问匹配值?
How to access the matched value in the default case of structural pattern matching?
用Python3.10的match语句,是否可以使用默认情况下met的值?
或者这个是否需要在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?
)
您可以使用 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)}")
用Python3.10的match语句,是否可以使用默认情况下met的值?
或者这个是否需要在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?
)
您可以使用 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)}")