使用 Python (2.7) 三元表达式 x if cond else y 在按顺序评估这些嵌套的多个表达式时的逻辑顺序是什么:例如
1 if A else 2 if B else 3
为此得出真值表 this is evaluated as 1 if A else (2 if B else 3) 而不是 (1 if A else 2) if B else 3 :
A True False
B
True 1 2
False 1 3
谁能解释一下为什么按这个顺序执行,并可能提供一些 Material 来直观地说明为什么使用/首选这个?
考虑使用内联 for 语句进行排序时,这似乎并不明显:
>>>[(i, j, k) for i in range(1) for j in range(2) for k in range(3)]
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2)]
请您参考如下方法:
1 if A else 2 if B else 3 转换为:
def myexpr(A, B):
if A:
return 1
else:
if B:
return 2
else:
return 3
您的三元表达式可以用括号解释如下:
(
(1 if A) else (
(2 if B) else 3
)
)
