【问题标题】:Faster "switch-case" implementation in pythonpython中更快的“switch-case”实现
【发布时间】:2018-12-17 11:58:54
【问题描述】:

我编写了下面的脚本来读取字符串缓冲区并将数字分配到 6 个不同的变量中。我在 C# 中找到了一个使用 switch-case 方法执行相同操作的示例,当我在 python 中尝试类似方法时(如下所示),我得到了想要的结果,但是读取缓冲区需要太多时间(超过一秒) .这个脚本只是一种测试方法,它会成为更大的开环控制代码的一部分,所以循环时间真的很重要。在python中有没有更快的方法?我使用python 2.7。先感谢您。

Julio = '123.5,407.4,21.6,9.7,489.2,45.9/\n'

letter = ''
x_c = '' 
y_c = '' 
z_c = '' 
theta_c = '' 
ux_c = '' 
uy_c = '' 
variable_number = 1

def one():
    global x_c
    x_c += letter

def two():
    global y_c
    y_c += letter

def three():
    global z_c
    z_c += letter

def four():
    global theta_c
    theta_c += letter

def five():
    global ux_c
    ux_c += letter

def six():
    global uy_c
    uy_c += letter

def string_reader(variable_number):
    switcher = {
        1: one,
        2: two,
        3: three,
        4: four,
        5: five,
        6: six
    }
    # Get the function from switcher dictionary
    func = switcher.get(variable_number, lambda: 'Invalid variable number')
    # Execute the function
    print func()

for letter in Julio:
    if (letter != '/') and (letter != ',') and (letter != '\n'):
        string_reader(variable_number)
    elif (letter == '/'):
        break
    elif (letter == '\n'):
        break
    else:
        variable_number = variable_number + 1


print x_c, y_c, z_c, theta_c, ux_c, uy_c

【问题讨论】:

    标签: python-2.7 stringbuffer


    【解决方案1】:

    呃……你不是把事情复杂化了吗?

    >>> Julio = '123.5,407.4,21.6,9.7,489.2,45.9/\n'
    >>> x_c, y_c, z_c, theta_c, ux_c, uy_c = Julio.strip().rstrip("/").split(",")[:6]
    

    【讨论】:

    • 我是 Python 新手,所以如果问题太琐碎,我很抱歉。我检查了你的方式,它工作正常。我还使用 float 函数将字符串转换为十进制数以执行算术运算。
    • 仅仅阅读你的代码就足以猜测你没有太多的 Python 经验,所以不要抱歉 ;-)
    猜你喜欢
    • 2019-11-18
    • 2022-06-14
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 2019-04-07
    • 2021-06-13
    • 2019-10-02
    相关资源
    最近更新 更多