当else做得最多的时候,最有效的方式来执行if-elif-elif-else语句吗?

我有一条if-elif-elif-else语句,其中99%的时间执行else语句:


if something == 'this':

    doThis()

elif something == 'that':

    doThat()

elif something == 'there':

    doThere()

else:

    doThisMostOfTheTime()

这个构造完成了很多,但是由于它在碰到其他情况之前会遍历所有条件,所以我觉得这不是很有效,更不用说Pythonic了。另一方面,它确实需要知道是否满足任何这些条件,因此无论如何都应该对其进行测试。


是否有人知道是否以及如何才能更有效地完成此工作,或者这仅仅是做到这一点的最佳方法?


动漫人物
浏览 396回答 3
3回答

斯蒂芬大帝

你可以使用pypy吗?保留原始代码,但在pypy上运行可使我的速度提高50倍。CPython:matt$ pythonPython 2.6.8 (unknown, Nov 26 2012, 10:25:03)[GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwinType "help", "copyright", "credits" or "license" for more information.>>>>>> from timeit import timeit>>> timeit("""... if something == 'this': pass... elif something == 'that': pass... elif something == 'there': pass... else: pass... """, "something='foo'", number=10000000)1.728302001953125pypy:matt$ pypyPython 2.7.3 (daf4a1b651e0, Dec 07 2012, 23:00:16)[PyPy 2.0.0-beta1 with GCC 4.2.1] on darwinType "help", "copyright", "credits" or "license" for more information.And now for something completely different: ``a 10th of forever is 1h45''>>>>>>>> from timeit import timeit>>>> timeit(""".... if something == 'this': pass.... elif something == 'that': pass.... elif something == 'there': pass.... else: pass.... """, "something='foo'", number=10000000)0.03306388854980469
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python