假设我们有一定数量的可能字符串:possible_strings_list = ['foo', 'bar', 'baz', 'qux', 'spam', 'ham', 'eggs']
并接收新的字符串,这是已知的其中之一。例如,我们希望为每个新字符串分配一个整数
^{pr2}$
在Python3.6中实现这一点的最快方法是什么?
我尝试了几种方法,使用字典是目前最快的:
^{3}$
不过,我或多或少是一个Python新手,我对是否有其他更快的解决方案感兴趣。你有什么建议吗?在
我的完整测试代码: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 3
elif i == 'qux':
return 4
elif i == 'spam':
return 5
elif i == 'ham':
return 6
elif i == 'eggs':
return 7
def ternary(i):
return 0 if i == 'foo' else 1 if i == 'baz' else 2 if i == 'bar' else 3 if i == 'qux' else 4 if i == 'spam'else 5 if i == 'ham' else 6
n = lambda i: 0 if i == 'foo' else 1 if i == 'baz' else 2 if i == 'bar' else 3 if i == 'qux' else 4 if i == 'spam'else 5 if i == 'ham' else 6
def lambda_function(i):
return n(i)
def np_where(i):
return np.where(possible_strings_array == i)[0][0]
##
def check(function):
for i in testlist:
function(i)
possible_strings_list = ['foo', 'bar', 'baz', 'qux', 'spam', 'ham', 'eggs']
testlist = [random.choice(possible_strings_list) for i in range(1000)]
possible_strings_dict = {'foo':0, 'bar':1, 'baz':2, 'qux':3, 'spam':4, 'ham':5, 'eggs':6}
possible_strings_tup = ('foo', 'bar', 'baz', 'qux', 'spam', 'ham', 'eggs')
allfunctions = [list_index, dictionary, if_elif_else, lambda_function, tupple_index, ternary, np_where]
for function in allfunctions:
t = timeit.Timer(lambda: check(function))
print(function.__name__, t.timeit(number=10000))