使用and/or组合在python中实现三元运算符

2024-06-09 12:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python,使用的是marklutz的优秀书籍。我在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新手。提前谢谢。在


Tags: orandif方式语法情况运算符语句
2条回答

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

#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)

你应该改变输入并检查输出。但是,您直接更改输出并尝试检查输出,但这不起作用。所以,你的测试方法是错误的。 这里的输入是a。 这里的输出是b。 案例1: b=12个 a=1 c=20

^{pr2}$

你说得对,第二种方法在大多数情况下都很好。在

来自python文档:

Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators: [expression] and [on_true] or [on_false]

之后他们提到:

"However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the ... if ... else ... form.

以下是参考资料: 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) 

相关问题 更多 >