Python是否具有与“切换”相同的功能?

时间:2009-09-15 20:41:33

标签: python syntax switch-statement

我正在尝试检查8位二进制字符串中的每个索引。如果是'0'则为'OFF',否则为'ON'

是否有更简洁的方法来编写具有类似开关功能的代码。?

5 个答案:

答案 0 :(得分:32)

不,不。说到语言本身,Python的核心原则之一就是只有一种方法可以做某事。该开关是多余的:

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

(当然没有落空)。

该交换机最初是作为C的编译器优化引入的。现代编译器不再需要这些提示来优化这种逻辑语句。

答案 1 :(得分:10)

请改为尝试:

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]

答案 2 :(得分:3)

从 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")

将此作为未来遇到此问题的每个用户的答案。由于有关此主题的大多数热门问题已经关闭,因此我已经写了 this other StackOverflow answer,其中我试图涵盖您可能需要了解或关注的关于 match 的所有内容。

答案 3 :(得分:2)

else-如果是不好的做法,因为当它们太长时它们是不安全的,并且涉及不必要的条件分支(可能影响编译器/缓存)。

试试这个......

class Functions():
    @staticmethod
    def func():
        print("so - foo")
    @staticmethod
    def funcWithArgs( junk ):
        print(junk, "foo")

# fill in your cases here...
cases = {
    "a" : Functions.func ,
    "b" : Functions.funcWithArgs ,
    "c" : Functions.funcWithArgs
}

def switch( ch, cases, *args ):
    try:
        len(*args)  # empty args
    except TypeError:
        return cases[ ch ]( )
    return cases[ ch ]( *args )

# try out your switch...
switch("a", cases)  # "so - foo"
switch("b", cases, "b -")  # "b - foo"
switch("c", cases, "c -")  # "c - foo"

答案 4 :(得分:-1)

switch语句在C语言中非常有用。在python中,它可以在大多数情况下用字典替换。我认为switch语句在实现状态机时也非常有用,python不能替代它。它通常导致长函数的“不良”编程风格。但是是switch语句,将状态功能分为几部分。在python中,如果-必须使用elif构造。 switch语句的大多数用法可以用一种更优雅的方式替换,有些则可以用一种不太优雅的方式替换。

相关问题