Python:评估所有/任何vs拼写出来的

时间:2018-01-27 11:06:08

标签: python performance if-statement logic

让我们考虑两种检查所有条件为真的方法

选项1

if all([cond1, cond2, cond3]):
  return true

选项2

if (cond1 and cond2 and cond3):
  return true

两者都以同样的方式评估吗? AFAIR all一旦语句失败就会失败,这使得条件可以假设所有先前列出的条件都评估为true。例如。在选项1中安全地访问cond3中的变量,该变量之前(在cond1cond2中)经过测试可访问。对于选项2,这也适用吗?还有性能差异吗?

1 个答案:

答案 0 :(得分:2)

选项1具有额外的性能开销,需要创建列表,然后遍历列表。还有一个问题,即在检查真实性之前必须计算all()中使用的迭代中的每个条件。

@StefanPochmann的一个很好的例子证明了出现的问题:

a = [3, 1, 4, 1, 5, 9]

if a and a[0] > 5:
    pass

if all((a, a[0] > 5)):
    pass

a = []

if a and a[0] > 5:
    pass

if all((a, a[0] > 5)):
    pass

Traceback (most recent call last):
  File "/tmp/execpad-b1260aab7279/source-b1260aab7279", line 14, in <module>
    if all((a, a[0] > 5)):
IndexError: list index out of range

您可以看到代码段运行here

使用选项2是更好的选择,除非您实际验证布尔值列表。如上所示,使用and运算符可以防止检查超过第一个失败的转义。

除了性能原因之外,如果您在条件之间使用and运算符,则代码更容易阅读。在编辑器中使用适当的语法hilighting,将会非常清楚发生了什么。