在Python中,没有内置的`switch-case`语句,但可以通过多种方式模拟实现。以下是几种常见的方法:
方法一:使用字典映射
```python
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语句```pythondef 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)
方法三:使用类实现
```python
class Switch(object):
def __init__(self, case_path):
self.switch_to = case_path
self._invoked = False
def case(self, key, method):
if self.switch_to == key and not self._invoked:
self._invoked = True
method()
return self
def default(self, method):
if not self._invoked:
self._invoked = True
method()
调用函数
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及以上版本)```pythoncolor = input("请输入需要查询的颜色:")
match color:
case 'red' | '红' | '红色':
r, g, b = 255, 0, 0
case 'green' | '绿' | '绿色':
r, g, b = 0, 255, 0
case 'yellow' | '黄' | '黄色':
r, g, b = 255, 255, 0
case _:
r, g, b = -1, -1, -1
if r >= 0:
print(f"{color}的颜色代码:{r:02X}{g:02X}{b:02X}")
else:
print(f"查询不到{color}的颜色代码!")
以上是Python中模拟`switch-case`语句的几种方法。您可以根据需要选择合适的方法来实现类似的功能

