【问题标题】:Can I use list slicing on my match/case term in Python3我可以在 Python3 中对我的匹配项/案例项使用列表切片吗
【发布时间】:2023-01-18 23:27:10
【问题描述】:

详细说明我有一个字符串x,它的结构是

"Test_Case_Box 1"
"Test_Case_Box 2"
"Test_Case_Circle 1"

我正在使用 ifelif 语句通过检查例如 if

x[0:19] == "Test_Case_Box"

使用匹配/大小写语法,如果我将 term 设置为我的字符串 x,我仍然可以创建 if like cases,例如

match x:
                case x[0:10] == 'Request_Fun':
                    print(f'-- x[0:10]: {x[0:10]}')

【问题讨论】:

  • 是什么阻止你尝试?

标签: python list switch-statement match


【解决方案1】:

是的,但只有卫兵.但我认为这不是 match 语句的真实用例。 If you're not matching the structure of the subject, structural pattern matching probably isn't the right tool for the job否则使用if-else声明。

x = "Test_Case_Box 1"
match x:
    case x if x[0:10] == 'Test_Case_':
        print("Here")
    case _:
        print("DEFAULT")

【讨论】:

  • 如果我仍然需要使用 Gurds,那么使用这种类型的匹配/大小写比 if/elif 语句有什么好处。你提供的方法?
【解决方案2】:

无需使用切片。要使用match的全部好处,您可以split输入:

strs = ["Test_Case_Box 1", "Test_Case_Box 2", "Test_Case_Circle 3"]

for s in strs:
    match s.split():
        case ["Test_Case_Box", num]:
            print(num)

将打印:

1
2

在这里使用match 的好处是您可以一次性获得结构匹配和分配变量。例如,使用 if/elif 您需要解析结构,然后在条件内解析以提取数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多