更快的替代方案
list.index
你可以建造一个
dictionary
of letter:索引对使用
enumerate
:
yourlist = list('DRAGON')
yourdict = {letter: idx for idx, letter in enumerate(yourlist)}
guess = input('What letter do you want to guess?')
result = yourdict.get(guess.strip()) # Avoids KeyError on missing letters
if result is not None:
print("You got it!", result)
else:
print("Nope!")
对于短名单,
列表索引
完全没问题,你不会注意到
dict
,但对于非常长的列表,它会产生影响:
短名单
列表
python -m timeit -s 'x = list(range(50))' 'x.index(49)'
1000000 loops, best of 3: 0.584 usec per loop
迪克特
python -m timeit -s 'x = dict(enumerate(list(range(50))))' 'x.get(49)'
10000000 loops, best of 3: 0.0733 usec per loop
# at this level, you really won't notice the difference on a GHz processor
长列表
列表
python -m timeit -s 'x = list(range(500000))' 'x.index(490000)'
100 loops, best of 3: 4.91 msec per loop
迪克特
python -m timeit -s 'x = dict(enumerate(list(range(500000))))' 'x.get(490000)'
10000000 loops, best of 3: 0.0884 usec per loop
注意,对于大量的项目,
迪克特
规模真的很好