python查找字符最快_执行字符串查找的最快方法?

假设我们有一定数量的可能字符串: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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值