当else完成时,制作if

编程入门 行业动态 更新时间:2024-10-10 15:17:56
本文介绍了当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

本文发布于:2023-11-30 09:48:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649552.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!