【问题标题】:How may i use switch statement in python (for multiple case same value)[python]我如何在 python 中使用 switch 语句(对于多个情况相同的值)[python]
【发布时间】:2020-12-20 09:16:36
【问题描述】:

我想在 python 中使用一个开关,我该如何使用它。假设如果我想为 90 分以上的学生分配一个评分系统,将获得 A 级以下,使用 switch 将获得 B 级

请帮忙!!!

【问题讨论】:

  • 如果这是您的标准,高于 90 为 A,低于 90 为 B,那么即使 Python 中确实存在 switch,它也不是合适的工具。
  • 这里可以使用if-else,切换请参考stackoverflow.com/questions/60208/…

标签: python switch-statement case


【解决方案1】:

Python 没有 switch 语句。要在 Python 中实现类似的功能,您可以使用if/elif/else(这对您的示例非常适用)或使用字典的查找表。

【讨论】:

    【解决方案2】:

    您可以使用以下函数定义模拟 switch 语句:

    def switch(v): yield lambda *c: v in c
    

    你可以在 C 风格中使用它:

    x = 3
    for case in switch(x):
    
        if case(1):
            # do something
            break
    
        if case(2,4):
            # do some other thing
            break
    
        if case(3):
            # do something else
            break
    
    else:
        # deal with other values of x
    

    或者您可以使用 if/elif/else 模式而不使用中断:

    x = 3
    for case in switch(x):
    
        if case(1):
            # do something
    
        elif case(2,4):
            # do some other thing
    
        elif case(3):
            # do something else
    
        else:
            # deal with other values of x
    

    对于函数调度来说特别有表现力

    functionKey = 'f2'
    for case in switch(functionKey):
        if case('f1'): return findPerson()
        if case('f2'): return editAccount()
        if case('f3'): return saveChanges() 
    

    【讨论】:

      猜你喜欢
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      相关资源
      最近更新 更多