Python多重嵌套三元表达式 [英] Python multiple nested ternary expression
问题描述
使用Python(2.7)三元表达式 x表示否y
当按顺序嵌套这些表达式的多个表达式时,逻辑顺序是什么?例如
With the Python (2.7) ternary expression x if cond else y
what is the logical order when evaluating multiple expressions of these nested in order: e.g.
1 if A else 2 if B else 3
为此绘制出真值表,似乎如果A否则其评估为 1(如果B否则3评估为2)
而不是(如果A否则为1则为2)如果B否则为3 :
Drawing out the truth table for this is appears this is evaluated as 1 if A else (2 if B else 3)
rather than (1 if A else 2) if B else 3
:
A True False
B
True 1 2
False 1 3
有人可以解释一下为什么以这种顺序执行此操作,并可能建议一些可以直观了解为什么使用/首选方法的材料?
Could someone please explain why this is executed in this order, and possibly suggest some material that gives an intuition about why this is used/preferred?
在考虑顺序时,这似乎并不明显使用内嵌的 for
语句:
This doesn't seem obvious when considering the ordering using the inline for
statement:
>>>[(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,如果A否则为2,如果B则为3
转换为:
def myexpr(A, B):
if A:
return 1
else:
if B:
return 2
else:
return 3
您的三元表达式可以用括号解释如下:
Your ternary expression can be interpreted with parentheses as follows:
(
(1 if A) else (
(2 if B) else 3
)
)
这篇关于Python多重嵌套三元表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!