这并不是一个真正的答案,但很多评论都集中在性能上,因为我确实问过。因此,到目前为止,我对答案进行了一些性能测试:
from datetime import datetime
from string import maketrans
tr_table = maketrans('IEDM', '+-:.')
dictionary = { "I":"+", "E":"-", "D":":", "M":"." }
if_else_val = "E"
N_OPS = 100000
now = datetime.now
def time(func):
s = now()
func()
print "%s took %d ms for %d operations" % (func.__name__, (now() - s).microseconds, N_OPS)
def translation_table():
for i in xrange(N_OPS):
"I".translate(tr_table)
"E".translate(tr_table)
"D".translate(tr_table)
"M".translate(tr_table)
def dict_lookup():
for i in xrange(N_OPS):
dictionary.get("I")
dictionary.get("E")
dictionary.get("D")
dictionary.get("M")
def if_else():
for i in xrange(N_OPS):
if if_else_val == "I": pass
elif if_else_val == "E": pass
elif if_else_val == "D": pass
elif if_else_val == "M": pass
time(if_else)
time(translation_table)
time(dict_lookup)
结果如下:
if_else took 12474 ms for 100000 operations
translation_table took 81650 ms for 100000 operations
dict_lookup took 66385 ms for 100000 operations