I'm hoping there's no performance or other disadvantage in attempting to avoid long chains of conditional if/elif statements this way:
我希望在尝试以这种方式避免条件if / elif语句的长链时没有性能或其他缺点:
errstr = {404: "404 Not Found",
405: "405 Method Not Allowed"}
if code in errstr:
print errstr[code];
1 个解决方案
#1
4
Yes, they're the best solution, because they are implemented as hash tables, giving approximately constant lookup times (if the hash function is good). Binary trees would give logarithmic lookup time, if
chains linear time. Hash tables are usually the way to go if one has to represent a mapping from a not-too-large finite set to some other set.
是的,它们是最好的解决方案,因为它们被实现为哈希表,提供大致恒定的查找时间(如果哈希函数是好的)。如果链线性时间,二叉树将给出对数查找时间。如果必须表示从不太大的有限集到其他集的映射,散列表通常是要走的路。
BTW, Python is a very good language for learning, because in Python, often the simplest solution is also the best one.
顺便说一句,Python是一种非常好的学习语言,因为在Python中,最简单的解决方案通常也是最好的。
#1
4
Yes, they're the best solution, because they are implemented as hash tables, giving approximately constant lookup times (if the hash function is good). Binary trees would give logarithmic lookup time, if
chains linear time. Hash tables are usually the way to go if one has to represent a mapping from a not-too-large finite set to some other set.
是的,它们是最好的解决方案,因为它们被实现为哈希表,提供大致恒定的查找时间(如果哈希函数是好的)。如果链线性时间,二叉树将给出对数查找时间。如果必须表示从不太大的有限集到其他集的映射,散列表通常是要走的路。
BTW, Python is a very good language for learning, because in Python, often the simplest solution is also the best one.
顺便说一句,Python是一种非常好的学习语言,因为在Python中,最简单的解决方案通常也是最好的。