python中最好的方法是什么?if语句中有多个OR或IN吗? [英] What is the best approach in python: multiple OR or IN in if statement?
问题描述
如果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屋!