2

any在 Python 3 中,是否可以在没有for .. in表达式的调用中使用短路评估?

我知道我可以在这样的语句中利用短路评估:

print('Hello' if True or 3/0 else 'World')  # this prints "Hello"

但是如果我尝试与 类似的东西any,我会得到一个异常,因为3/0被评估:

print('Hello' if any([True, 3/0]) else 'World')  # this raises an exception

有没有办法可以any用来做到这一点?

4

1 回答 1

1

这里的问题不是any,而是在评估3/0列表文字时立即评估:

>>> [True, 3/0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

避免这种情况的唯一方法是使用函数或迭代器将评估延迟到以后:

def f(e):
    return e[0]/e[1] if isinstance(e,(list,tuple)) else e

>>> print('Hello' if any(map(f, [True, [3,0]])) else 'World')
Hello
于 2021-03-09T20:46:49.090 回答