我会创建一个字典:
options = {'this': doThis,'that' :doThat, 'there':doThere}
现在只使用:
options.get(something, doThisMostOfTheTime)()
如果在字典something
中找不到,则返回默认值options
dict.get
doThisMostOfTheTime
一些时间比较:
脚本:
from random import shuffle
def doThis():pass
def doThat():pass
def doThere():pass
def doSomethingElse():pass
options = {'this':doThis, 'that':doThat, 'there':doThere}
lis = range(10**4) + options.keys()*100
shuffle(lis)
def get():
for x in lis:
options.get(x, doSomethingElse)()
def key_in_dic():
for x in lis:
if x in options:
options[x]()
else:
doSomethingElse()
def if_else():
for x in lis:
if x == 'this':
doThis()
elif x == 'that':
doThat()
elif x == 'there':
doThere()
else:
doSomethingElse()
结果:
>>> from so import *
>>> %timeit get()
100 loops, best of 3: 5.06 ms per loop
>>> %timeit key_in_dic()
100 loops, best of 3: 3.55 ms per loop
>>> %timeit if_else()
100 loops, best of 3: 6.42 ms per loop
对于10**5
不存在的密钥和 100 个有效密钥:
>>> %timeit get()
10 loops, best of 3: 84.4 ms per loop
>>> %timeit key_in_dic()
10 loops, best of 3: 50.4 ms per loop
>>> %timeit if_else()
10 loops, best of 3: 104 ms per loop
因此,对于普通字典,检查键 usingkey in options
是这里最有效的方法:
if key in options:
options[key]()
else:
doSomethingElse()