为什么所有的行为都不同于简单的短路条件
为什么all行为与if这种情况不同?
In [1]: a = []
In [2]: if a and a[1]: # short circuiting -> no exception
...: pass
...:
In [3]: all((a, a[0])) # a[0] is evaluated before the condition is evaluated -> exception
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-3-a381b7aa45b3> in <module>()
----> 1 all((a, a[0]))
IndexError: list index out of range
回答
In [3]: all((a, a[0])) # a[0] is evaluated before the condition is evaluated -> exception
不同之处在于,当您调用函数时,Python 会计算所有参数,然后将它们的值传递给函数。所以在这里a和a[0]被评估以创建一个tuple. 那么tuple传递给all()成功创建它。