繁体   English   中英

使用和/或组合在python中实现三元运算符

[英]implementing ternary operator in python using and/or combinations

我正在使用Mark Lutz的优秀著作来学习python。 我遇到了以下声明,即python中的三元运算符,实际上是这样的:

if a: 
   b
else: 
   c

可以用两种方式编写:

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

  2. ((a and b) or c) :使用等效但比较棘手的and/or组合

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

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

看来,2个表达式是等效的所有truthy的值b ,但不等同于所有falsy的值b

我想知道,这里有什么我想念的。 我的分析错了吗? 为什么在书中这么说两个案例是相等的。 请启发我的粗心。 我是python的新手。 提前致谢。

没错,在大多数情况下,第二种方法很棒。

从python文档中:

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

之后,他们提到:

“但是,这种习惯用法是不安全的,因为当on_true具有错误的布尔值时,它会产生错误的结果。因此,最好使用... if ... else ...形式。

这是参考: https : //docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-cs-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) 

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

#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并尝试检查输出,则该输出不起作用。 因此,我认为您正在测试错误的方式。 输入是一个。 这里的输出是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.*

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM