[英]Fastest way to check for multiple conditions
I am looking to check for 3 conditions, any of which triggers a continue.我正在寻找 3 个条件,其中任何一个都会触发继续。
The 2 ways I am looking at are 1) if with multiple conditions 2) if and elif我正在查看的 2 种方法是 1) if 有多个条件 2) if 和 elif
def conditions_1(a,b,c):
numbers = []
min_no = min(a,b,c)
max_no = max(a,b,c)
for no in range(min_no,max_no+1):
if no == 0 :
continue
elif no + min_no == 0:
continue
elif math.gcd(min_no, no)> 1:
continue
else:
numbers.append(no)
return(numbers)
def conditions_2(a,b,c):
numbers = []
min_no = min(a,b,c)
max_no = max(a,b,c)
for no in range(min_no,max_no+1):
if no == 0 or no + min_no == 0 or math.gcd(min_no, no)> 1:
continue
else:
numbers.append(no)
return(numbers)
for _ in range(10):
t0 = time.time()
conditions_1(-5000, 10000, 4)
t1 = time.time()
conditions_2(-5000, 10000, 4)
t2 = time.time()
if t2-t1 > t1-t0:
print('2nd')
else:
print('1st')
May I know if there is a difference in both ways?我可以知道这两种方式是否有区别吗?
Thanks to the fact that or
has short-circuit evaluation (ie, it evaluates the list of conditions left to right and stops at the first True), the execution pattern is the same between your two variants (minus the fact that in the if/elif case you may have multiple jumps when testing each condition).由于
or
具有短路评估的事实(即,它评估从左到右的条件列表并在第一个 True 处停止),您的两个变体之间的执行模式是相同的(减去在 if/ elif 情况下,您在测试每个条件时可能会有多次跳转)。
Coding-style-wise, the second is of course a lot better (no repetition of continue
, clearer intent of the if/else block) and should be the way you structure your code.就编码风格而言,第二个当然要好得多(不重复
continue
, if/else 块的意图更清晰),应该是您构建代码的方式。
Side note: Remember that if an expression gets too long, you can put it in parentheses and break it over several lines:旁注:请记住,如果表达式太长,您可以将其放在括号中并将其分成几行:
if (some_very_lengthy_condition_1 == my_very_lengthy_name_1 or
some_very_lengthy_condition_2 == my_very_lengthy_name_2 or
some_very_lengthy_condition_3 == my_very_lengthy_name_3 ):
pass # do something
As Gábor noted in the comments, in python you also have the any
and all
operators, which apply to iterables.正如 Gábor 在评论中指出的那样,在 python 中,您还拥有适用于可迭代对象的
any
和all
运算符。 any(iterable)
is equivalent to or
ing all values in the iterable, while all(iterable)
is equivalent to and
ing them. any(iterable)
等价于or
ing iterable 中的所有值,而all(iterable)
等价于and
ing 它们。 Short-circuit logic applies here as well, so that only the minimal number of values in iterable
are evaluated when computing the expression result.短路逻辑也适用于此,因此在计算表达式结果时,只计算
iterable
的最小数量的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.