Python 有类似于 'switch' 的语法吗?

30 投票
6 回答
50864 浏览
提问于 2025-04-15 14:21

我想检查一个8位的二进制字符串中的每个位置。如果这个位置是 '0',那么我就认为它是 'OFF',否则就是 'ON'

有没有更简洁的方法来写这段代码,像开关一样的功能?

6 个回答

8

从Python 3.10.0开始 (alpha6版本于2021年3月30日发布),现在有了一个官方的真正的语法等价物!


digit = 5
match digit:
    case 5:
        print("The number is five, state is ON")
    case 1:
        print("The number is one, state is ON")
    case 0:
        print("The number is zero, state is OFF")
    case _:
        print("The value is unknown")

我写了这篇其他的Stack Overflow回答,在里面我尽量涵盖了你可能需要知道或处理的关于match的所有内容。

13

试试这个:

def on_function(*args, **kwargs):
    # do something

def off_function(*args, **kwargs):
    # do something

function_dict = { '0' : off_function, '1' : on_function }

for ch in binary_string:
   function_dict[ch]()

或者,如果你的函数有返回值的话,你可以使用列表推导式或者生成器表达式:

result_list = [function_dict[ch]() for ch in binary_string]
42

不,它并不是这样。关于语言本身,Python的一个核心原则就是尽量只提供一种做事情的方法。所以,switch语句在这里是多余的:

if x == 1:
    pass
elif x == 5:
    pass
elif x == 10:
    pass

(当然,这里不考虑“贯穿”情况)。

switch语句最初是为了优化C语言的编译器而引入的。但现代编译器已经不再需要这些提示来优化这种逻辑语句了。

撰写回答