【问题标题】:implementing ternary operator in python using and/or combinations使用和/或组合在python中实现三元运算符
【发布时间】:2018-11-07 05:39:49
【问题描述】:

我正在使用 Mark Lutz 的优秀书籍学习 python。我遇到了python中的三元运算符的这种说法,实际上是这样的:

if a: 
   b
else: 
   c

可以写成两种方式:

  1. b if a else c : 使用python的普通三元语法和

  2. ((a and b) or c) :使用等效但更复杂的 and/or 组合

我发现第二种表示令人不安,因为它不符合我的直觉。我在交互式提示符下尝试了这两种语法,并为 b = 0. 的特殊情况找到了不同的答案(假设 b = 0,a = 4,c = 20)

  1. 0 if 4 else 20 输出 0
  2. ((4 and 0) or 20) 输出 20

这两个表达式似乎与b 的所有truthy 值等效,但对于b 的所有falsy 值并不等效。

我想知道,这里有什么我遗漏的。我的分析错了吗?为什么书中说这两种情况是等价的。请开导我粗糙的头脑。我是 python 新手。提前致谢。

【问题讨论】:

  • 不,您似乎做对了。一定是你正在看的书,关于第二种方式什么时候等于第一种方式有点模糊。
  • 不,你是对的。你不应该使用它,因为你所说的原因,它是危险的。在三元运算符之前,另一个成语是[c, b][bool(a)],如果a是布尔表达式,可以省略bool
  • @juanpa.arrivillaga 这个成语[c,b][bool(a)] 听起来很酷很创新。对于任何此类特殊情况,它是否也会失败?我希望不会。
  • @Gsbansal10 这并不酷,它是 hackey。使用条件表达式或完整的条件语句。

标签: python ternary-operator


【解决方案1】:

你是对的,第二种方法在大多数情况下都很棒。

来自 python 文档:

在 Python 2.5 中引入这种语法之前,一个常见的习惯用法是 使用逻辑运算符:[表达式] 和 [on_true] 或 [on_false]

紧接着他们提到:

“但是,这个成语是不安全的,因为它可能会在以下情况下给出错误的结果 on_true 有一个假布尔值。因此,最好总是 使用 ... if ... else ... 形式。

这是一个参考: https://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator

为每个请求添加简短示例:

a = True
b = False
c = True

# prints False (for b) correctly since a is True
if a:
   print b
else: 
   print c

# prints False (for b) correctly since a is True
print b if a else c 

# prints True (for c) incorrectly since a is True and b should have been printed
print ((a and b) or c) 

【讨论】:

  • 你能给出一个分组语句何时失败的示例代码吗?
  • 当然,添加了一个简单的例子:)
  • 好多了!太棒了。
【解决方案2】:

这里作者的观点不同,应该考虑。让我尝试用代码和内联 cmets 来解释:

#This if condition will get executed always(because its TRUE always for any number) except when it is '0' which is equivalent to boolean FALSE.
#'a' is the input which the author intends to show here. 'b' is the expected output
if a: 
   print(b)
else: 
   print(c)

#equivalent
print(b) if a else print(c) 
print((a and b) or c)

您应该更改输入并检查输出。然而,您直接更改 OUTPUT 并尝试检查输出,但这是行不通的。因此,我认为您正在测试错误的方式。 这里的输入是 a。 这里的输出是 b。 案例 1: b = 12 a = 1 c = 20

*Case 2:
b = 12
a = 0
c = 20*
*Dont change 'b'. Change only 'a' and test is the conceptual idea. Coz, 'b' is the output.*

【讨论】:

    猜你喜欢
    • 2016-09-09
    • 1970-01-01
    • 2016-08-20
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2016-03-10
    • 2012-01-20
    相关资源
    最近更新 更多