当else完成时,制作if-elif-elif-else语句的最有效方法是什么? [英] Most efficient way of making an if-elif-elif-else statement when the else is done the most?

查看:164
本文介绍了当else完成时,制作if-elif-elif-else语句的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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()

这个结构已经很多,但是因为它在它击中其他条件之前会超过每个条件我感觉这不是很有效,更不用说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)()

...看起来它应该更快,但它实际上比更慢,如果 ... 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.

请考虑以下示例......

Consider these examples...

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

...使用 时间的用户时间(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语句的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆