python中的最佳方法是什么:if语句中的多个OR或IN? [英] What is the best approach in python: multiple OR or IN in if statement?
问题描述
python 中最好的方法是什么:multiple OR 或 IN in if 语句?考虑性能和最佳实践.
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': pass
或
if cond in ['1','2','3','4']: pass
推荐答案
最好的方法是使用set:
if cond in {'1','2','3','4'}:
因为集合中的成员资格测试是 O(1)(恒定成本).
as membership testing in a set is O(1) (constant cost).
另外两种方法的复杂度相同;只是不变成本的差异.列表上的 in
测试和 or
链短路;找到匹配项后立即终止.一个使用字节码跳转序列(如果 True
跳转到末尾),另一个使用 C 循环和如果值匹配则提前退出.在最坏的情况下,cond
与序列中的元素不匹配,任何一种方法都必须检查所有元素,然后才能返回<代码>假代码>.在这两者中,我会在任何一天选择 in
测试,因为它更具可读性.
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屋!