假设我们有一定数量的可能字符串:
possible_strings_list = ['foo', 'bar', 'baz', 'qux', 'spam', 'ham', 'eggs']
Run Code Online (Sandbox Code Playgroud)
并接收已知为其中之一的新字符串.例如,我们想为每个新字符串分配一个整数
if new_string == 'foo':
return 0
elif new_string == 'bar':
return 1
...
Run Code Online (Sandbox Code Playgroud)
在Python 3.6中最快的方法是什么?我尝试了几种方法,到目前为止使用字典是最快的:
list_index 2.7494255019701086
dictionary 0.9412809460191056
if_elif_else 2.10705983400112
lambda_function 2.6321219780365936
tupple_index 2.751029207953252
ternary 1.931659944995772
np_where 15.610908019007184
Run Code Online (Sandbox Code Playgroud)
然而,我或多或少是一个Python新手,如果有其他更快的解决方案,我很感兴趣.你有什么建议吗?
我完整的testig代码:
import timeit
import random
import numpy as np
def list_index(i):
return(possible_strings_list.index(i))
def dictionary(i):
return possible_strings_dict[i]
def tupple_index(i):
return possible_strings_tup.index(i)
def if_elif_else(i):
if i == 'foo':
return 1
elif i == 'bar':
return 2
elif i == 'baz':
return …Run Code Online (Sandbox Code Playgroud)