Python 多嵌套三元表达式

Python multiple nested ternary expression

提问人:oliversm 提问时间:6/20/2017 更新时间:9/7/2022 访问量:19235

问:

使用 Python (2.7) 三元表达式,在按顺序计算这些嵌套的多个表达式时,逻辑顺序是什么:例如x if cond else y

1 if A else 2 if B else 3

为此绘制真值表似乎是,这是评估的,而不是: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

有人可以解释为什么按这个顺序执行,并可能建议一些材料来直观地说明为什么使用/首选它?

在考虑使用内联语句进行排序时,这似乎并不明显: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)]
python for-loop 嵌套三 元运算符

评论

0赞 depperm 6/20/2017
for循环与三元条件不同
3赞 zwer 6/20/2017
机器人循环和三元条件从左到右评估,完全一样......
0赞 juanpa.arrivillaga 6/20/2017
这不是“内联声明”。
0赞 DomQ 8/14/2020
哇,没有一个受访者将你的问题理解为左联想问题——对于一种语法本身吸引无法解析的人的语言来说,这并不奇怪,但仍然......

答:

27赞 inspectorG4dget 6/20/2017 #1

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
               )
)
1赞 Love Tätting 6/20/2017 #2

布尔谓词在许多语言中被定义为尽可能快地终止,只要知道最终结果,特别是如果左边为真,则 or 表达式的右边根本不会被计算。它实际上与列表推导中发生的解构赋值无关。

评论

1赞 TemporalWolf 6/20/2017
这被称为短路
2赞 Prune 6/20/2017 #3

这两种用法都是它们相似结构的单线同源词。 已经为您布置了版本。 子句按给定顺序嵌套:inspectorG4dgetiffor

for i in range(1):
     for j in range(2):
         for k in range(3):
             result.append( (i, j, k) )

从解析器的角度来看,该部分的工作方式相同:当它命中时,解析器将作为顶级决策。根据语法的定义,这种嵌套是从右到左绑定的:是最里面的(内在的-更多?if1 if Aif Aif B

7赞 zurCalleD_suruaT 11/29/2018 #4

有人可以解释为什么按这个顺序执行,并可能建议一些材料来直观地说明为什么使用/首选它?

我试图通过解决一个简单但更普遍的问题来回答你问题的“直觉”部分。

'''
+-----------------------------------------------------------------------------------+
|                                    Problem:                                       |
+-----------------------------------------------------------------------------------+
| Convert a                                                                         |
| nested if-else block into                                                         |
| a single line of code by using Pythons ternary expression.                        |
| In simple terms convert:                                                          |
|                                                                                   |
|      1.f_nested_if_else(*args) (  which uses                                      |
|      ````````````````````        nested if-else's)                                |
|            |                                                                      |
|            +--->to its equivalent---+                                             |
|                                     |                                             |
|                                     V                                             |
|                              2.f_nested_ternary(*args) (     which uses           |
|                              ```````````````````       nested ternary expression) |
+-----------------------------------------------------------------------------------+
'''
'''
Note:
C:Conditions  (C, C1, C2)
E:Expressions (E11, E12, E21, E22)
Let all Conditions, Expressions be some mathematical function of args passed to the function
'''    

#-----------------------------------------------------------------------------------+
#| 1. |      Using nested if-else                                                   |
#-----------------------------------------------------------------------------------+
def f_nested_if_else(*args):
    if(C):
        if(C1):
            return E11
        else:
            return E12
    else:
        if(C2):
            return E21
        else:
            return E22

#-----------------------------------------------------------------------------------+
#| 2. |      Using nested ternary expression                                        |
#-----------------------------------------------------------------------------------+
def f_nested_ternary(*args):
    return ( (E11) if(C1)else (E12) )   if(C)else   ( (E21) if(C2)else (E22) )


#-----------------------------------------------------------------------------------+
#-----------------------------------------------------------------------------------|
#-----------------------------------------------------------------------------------|
#-----------------------------------------------------------------------------------|
#-----------------------------------------------------------------------------------+

这是 why 和 are 等价物的可视化。f_nested_if_else()f_nested_ternary()

#     +-----------------------------------------------------------------------------+
#     |                               Visualization:                                |
#     +-----------------------------------------------------------------------------+
#     |         Visualize the ternary expression like a binary tree :               |
#     |           -Starting from the root and  moving down to the leaves.           |
#     |           -All the internal nodes being conditions.                         |
#     |           -All the leaves being expressions.                                |
#     +-----------------------------------------------------------------------------+
                                     _________________
                                     |f_nested_ternary|                                 
                                     ``````````````````
            ( (E11) if(C1)else (E12) )   if(C)else   ( (E21) if(C2)else (E22) )
                |       |        |          |            |       |        |
                |       |        |          |            |       |        |
                V       V        V          V            V       V        V                                                                             
Level-1|                  +----------------(C)-----------------+         
--------             True/          __________________           \False         
                        V           |f_nested_if_else|            V              
Level-2|          +----(C1)----+    ``````````````````     +----(C2)----+     
--------     True/              \False                True/              \False
                V                V                       V                V     
Level-3|    ( (E11)            (E12) )               ( (E21)            (E22) ) 
------------------------------------------------------------------------------------+

希望此可视化能让您直观地了解如何计算嵌套的三元表达式:P

0赞 Jayen 9/7/2022 #5

1 if A else 2 if B else 3被解释为:

1 if A else (2 if B else 3)而不是:

(1 if A else 2) if B else 3