问题描述
我有一个 in if-elif-elif-else 语句,其中 99% 的时间执行 else 语句:
I've got a in if-elif-elif-else statement in which 99% of the time, the else statement is executed:
if something == 'this':
doThis()
elif something == 'that':
doThat()
elif something == 'there':
doThere()
else:
doThisMostOfTheTime()
这个构造做了很多,但是因为它在遇到else之前遍历了所有条件,所以我觉得这不是很有效,更不用说Pythonic了.另一方面,它确实需要知道是否满足这些条件中的任何一个,因此无论如何都应该对其进行测试.
This construct is done a lot, but since it goes over every condition before it hits the else I have the feeling this is not very efficient, let alone Pythonic. On the other hand, it does need to know if any of those conditions are met, so it should test it anyway.
有人知道是否可以以及如何更有效地完成这项工作,或者这仅仅是做到这一点的最佳方式吗?
Does anybody know if and how this could be done more efficiently or is this simply the best possible way to do it?
推荐答案
代码...
options.get(something, doThisMostOfTheTime)()
...看起来应该更快,但实际上比 if
... elif
... else
慢构造,因为它必须调用一个函数,这在紧密循环中可能是一个显着的性能开销.
...looks like it ought to be faster, but it's actually slower than the if
... elif
... else
construct, because it has to call a function, which can be a significant performance overhead in a tight loop.
考虑这些例子...
1.py
something = 'something'
for i in xrange(1000000):
if something == 'this':
the_thing = 1
elif something == 'that':
the_thing = 2
elif something == 'there':
the_thing = 3
else:
the_thing = 4
2.py
something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}
for i in xrange(1000000):
the_thing = options.get(something, 4)
3.py
something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}
for i in xrange(1000000):
if something in options:
the_thing = options[something]
else:
the_thing = 4
4.py
from collections import defaultdict
something = 'something'
options = defaultdict(lambda: 4, {'this': 1, 'that': 2, 'there': 3})
for i in xrange(1000000):
the_thing = options[something]
...并注意他们使用的 CPU 时间量...
...and note the amount of CPU time they use...
1.py: 160ms
2.py: 170ms
3.py: 110ms
4.py: 100ms
...使用来自 time(1)
.
...using the user time from time(1)
.
选项 #4 确实有额外的内存开销,为每个不同的键未命中添加一个新项目,所以如果您期望无限数量的不同键未命中,我会选择选项 #3,这仍然是一个对原始结构的显着改进.
Option #4 does have the additional memory overhead of adding a new item for every distinct key miss, so if you're expecting an unbounded number of distinct key misses, I'd go with option #3, which is still a significant improvement on the original construct.
这篇关于当 else 完成最多时,制作 if-elif-elif-else 语句的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!