在 python 中更快 "switch-case" 实施
Faster "switch-case" implementation in python
我编写了下面的脚本来读取字符串缓冲区并将数字分配到 6 个不同的变量中。我找到了一个使用 switch-case 方法在 C# 中执行相同操作的示例,当我在 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
呃……你是不是把事情搞得太复杂了?
>>> 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]
我编写了下面的脚本来读取字符串缓冲区并将数字分配到 6 个不同的变量中。我找到了一个使用 switch-case 方法在 C# 中执行相同操作的示例,当我在 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
呃……你是不是把事情搞得太复杂了?
>>> 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]