在Python中,没有内置的`switch-case`语句,但可以通过多种方式模拟实现。以下是几种常见的方法:
方法一:使用字典映射
def add(x, y):print(x + y)def minus(x, y):print(x - y)def multiply(x, y):print(x * y)def div(x, y):print(x / y)def fun_case_list(key, arg1, arg2):operator = {'+': add,'-': minus,'*': multiply,'/': div}if key in operator:return operator[key](arg1, arg2)else:return "No [%s] case in dic" % key[1:] or do other func调用函数fun_case_list('*', 3, 5)
方法二:使用if-elif-else语句
def case_example(x):if x > 0:print("x is positive")elif x < 0:print("x is negative")else:print("x is zero")调用函数case_example(5)
方法三:使用类实现
class Switch(object):def __init__(self, case_path):self.switch_to = case_pathself._invoked = Falsedef case(self, key, method):if self.switch_to == key and not self._invoked:self._invoked = Truemethod()return selfdef default(self, method):if not self._invoked:self._invoked = Truemethod()调用函数s = Switch('cn')s.case('cn', lambda: print('cn'))s.case('us', lambda: print('us'))s.default(lambda: print('default'))
方法四:使用`match-case`语法(Python 3.10及以上版本)
color = input("请输入需要查询的颜色:")match color:case 'red' | '红' | '红色':r, g, b = 255, 0, 0case 'green' | '绿' | '绿色':r, g, b = 0, 255, 0case 'yellow' | '黄' | '黄色':r, g, b = 255, 255, 0case _:r, g, b = -1, -1, -1if r >= 0:print(f"{color}的颜色代码:{r:02X}{g:02X}{b:02X}")else:print(f"查询不到{color}的颜色代码!")
以上是Python中模拟`switch-case`语句的几种方法。您可以根据需要选择合适的方法来实现类似的功能
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/137281.html