【发布时间】:2018-07-26 19:03:47
【问题描述】:
假设我们有一定数量的可能字符串:
possible_strings_list = ['foo', 'bar', 'baz', 'qux', 'spam', 'ham', 'eggs']
并接收已知为其中之一的新字符串。我们想为每个新字符串分配一个整数,例如
if new_string == 'foo':
return 0
elif new_string == 'bar':
return 1
...
在 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
但是,我或多或少是 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))
【问题讨论】:
-
据我所知,使用字典确实是最快的方法。我不希望您会找到更好的东西,因为这正是字典的预期用途。
-
并非如此,查找字典可能是您的最佳选择。
-
看起来您已经在进行性能测试了。请注意,随着列表大小的增加,您将获得不同的性能特征。一些方法将具有恒定时间、一些线性和一些指数。您是在测试特定的东西,还是只是一般情况?
-
@elpunkt 我不是真正的 python 大师,但我希望字典具有常量查找,如哈希表,但列表具有线性查找,因为需要检查每个值。因此,列表查找成本将取决于项目的位置(第一个比最后一个快),而字典则不然。
-
dict = python 中的哈希表,因此平均时间复杂度为 O(1),最差的是 O(n)。大多数用例都很难被击败(除非您搜索价值)
标签: python string python-3.x optimization