python中最好的方法是什么?if语句中有多个OR或IN吗? [英] What is the best approach in python: multiple OR or IN in if statement?

查看:689
本文介绍了python中最好的方法是什么?if语句中有多个OR或IN吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python中最好的方法是什么?if语句中的多个OR 或 IN 考虑性能和最佳规范。

 如果cond =='1'或cond =='2'或cond =='3 '或cond =='4'(etc ...):

  if ['1','2','3','4']:

谢谢。

解决方案

要使用

  if {'1','2' 3','4'}:

作为集合中的成员资格测试是O(1)(常数成本)。



其他两种方法在复杂性方面相同;只是不断的成本差异。 在列表中测试,链路短路;一旦找到匹配即终止。一个使用字节码跳转序列(如果 True 跳转到最后),另一个则使用C循环和早期退出(如果值匹配)。在最坏的情况下,其中 cond 不匹配序列中的元素,任何一种方法都必须检查所有元素之前可以返回 False 。在这两个中,我会在中选择,因为它的可读性更好。


What is the best approach in python: multiple OR or IN in if statement? Considering performance and best pratices.

if cond == '1' or cond == '2' or cond == '3' or cond == '4' (etc...) :

OR

if cond in ['1','2','3','4']:

Thank you.

解决方案

The best approach is to use a set:

if cond in {'1','2','3','4'}:

as membership testing in a set is O(1) (constant cost).

The other two approaches are equal in complexity; merely a difference in constant costs. Both the in test on a list and the or chain short-circuit; terminate as soon as a match is found. One uses a sequence of byte-code jumps (jump to the end if True), the other uses a C-loop and an early exit if the value matches. In the worst-case scenario, where cond does not match an element in the sequence either approach has to check all elements before it can return False. Of the two, I'd pick the in test any day because it is far more readable.

这篇关于python中最好的方法是什么?if语句中有多个OR或IN吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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